I Love the book “Metaprogramming Ruby” by Paolo Perrotta and found it very informative. The idioms defined in the book are so helpful. Here I have created a reference based on them for my own use. Hopefully it will help others too.

1) Dynamic Dispatch
Ruby allows us to dynamically call unknown methods(even private methods) on objects.

# object.send(message, *arguments)
2.send(:+, 3) # => 5
Read on →

Sometimes you may need to serve some static files (CSV, PDF, XLS etc) to your users, but only after they have logged in. Obviously you can’t just keep the static file in your public folder as anyone could just use the URL to download files.

One possible solution for protected downloads is to just use the #send_file method provided by Rack to send a non-public file to the user, but serving static files with your app server (Unicorn, Mongrel, Thin etc) is a bad idea as it’s really inefficient. The best approach is to allow the app server to handle the authentication/authorization and then hand the actual downloading to your web server (Nginx, Apache, Lighttpd etc).

Read on →

Active Resource supports defining our own custom REST methods. A custom method call is one that is not one of the default CRUD actions that you get out of the box with RESTful routing.

To invoke them, Active Resource provides the get, post, put and delete methods where you can specify a custom REST method name to invoke.

Read on →

Problem:

My application has a select box for users to choose a “mapping” for the upload. Based on mapping, user should see the default options selected in that form. When user changes the mapping, an AJAX request gets called and renders a js.erb file. The rendered js should render a partial that has fields_for a nested model. My challenge is, How to pass the form build object to the partial on AJAX callback?

Read on →