Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
calling class method in before filter
5 Posts
calling class method in before filter

Hey, recommend me if you have the chance ;)

wow what a wonderful explanation... Thanx a lot. In fact it's weired at the first instance to understand by looking the code. But these magics can be understood very well after such kind of explanation.....Bravo

Controller filters can be either the name of a method, a block, or in this case, a class that responds to a "filter" method. When invoked, the filter method is passed the instance of whichever controller you've declared it in.

For additional information, see the docs here: "ActionController::Filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html

There's a bit of magic going on there, but basically when Rails is about to call the filter it does a series of checks fo see if the supplied filter is a Symbol, String, Proc, or Method, and then does the appropriate thing with each case.

I.e. in case of Symbol it calls the method named in the symbol, in case of String it evaluates the string etc..

Now since in your example the result doesn't match any of the above cases the final check Rails does is to see if the supplied argument responds to "filter", and if so it will then call the "filter" method on the supplied object.

Now CASClient::Frameworks::Rails::Filter is a Module which actually contains the class method "filter". So when Rails asks "respons_to?(:filter)" it will return true, and Rails will then call that method...neat, eh? :)

The relevant magic bit is the "evaluate_method" defined in active_support/callbacks.rb: "callbacks.rb on GitHub":http://github.com/rails/rails/blob/575b95ea0bf3d3fff6f47dddad23c754fb294604/activesupport/lib/active_support/callbacks.rb#L176

Hope it helps..

Im using a ruby plugin and it asked me to use following code fragment as before filter.

before_filter CASClient::Frameworks::Rails::Filter

Then i went through the code and noticed that the class Filter in inside the modules Rails, Framworks,CASClient hierarchically. so in above code fragment it has mentioned only the class name (Filter) as before filter. But as far as i know we have to specify the method name in there. So how does this happen in this case. Is it something like default method taking care of the action? If so how does it identify it????

Thanx in advance

5 Posts
Login to add your message