Created
July 18, 2011 16:07
-
-
Save shreyas-satish/1089960 to your computer and use it in GitHub Desktop.
The send method - Ruby metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Consider a simple blogging app on Rails. Lets say, I have a list of articles, and I'd like to filter them by today's articles and this week's articles. | |
I'd like to define two methods in the model that does the actual filtering. | |
class Article < ActiveRecord::Base | |
def self.this_week | |
Article.where("created_at > ?", Date.today.beginning_of_week) | |
end | |
def self.today | |
Article.where("created_at > ?", Date.today) | |
end | |
end | |
So In my index.html.erb I have two links (in HAML, for brevity) : | |
= link_to "Filter by today", filter_articles_path(:time_range => "today") | |
= link_to "Filter by today", filter_articles_path(:time_range => "this_week") | |
Lets define a simple filter action in the articles controller : | |
def ArticlesController < ApplicationController | |
def filter | |
Article.send(params[:time_range]) | |
render :index | |
end | |
end | |
The send method dynamically decides which method to call. i.e it "sends" the argument as the method call. | |
So, in the example, if click on the "This week" link, the params[:time_range] will be "this_week" and Ruby in runtinme interprets | |
Article.send(params[:time_frame]) | |
as | |
Article.this_week | |
which invokes the class level "this_week" method we earlier declared in the Article model. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment