Possible Duplicate:
What is the order of ActiveRecord callbacks and validations?
I comes from the background of Java. One thing I think very weird in Rails is that you can set up call back functions like attributes just under the class, such as before_filter.
class SomeController < ActionController::Base
before_filter Proc.new {.....}
end
I don’t really understand how it works. I found this post which explains before_filter . I understand the flow of logic and it’s just a method. But I still don’t understand when will before_filter being executed to set up the callback chain.
before_filteris not a Ruby feature, it is a class method provided by Ruby on Rails (the web framework) that you can use in your controllers to execute a piece of code before executing any action in your controller.So, how does Ruby on Rails does that?
When you are defining a class in Ruby you are actually executing code, try this in irb:
You’ll see that “defining hello…” gets printed in the terminal when you define the class. You have not instantiated any object, you just have defined a class, but you can execute any code in the middle of defining a class.
You know that you can define “class methods” and “instance methods”, and what’s interesting is that you can call your class methods while you are still defining your class:
def self.add_componentdefines a class method that you can call while still defining your class. In this exampleadd_componentadds a keyboard to a list in a class variable, and thedef componentsinstance method (which is called on an instance of this class) access this class variable. The class method could have been defined in a parent class, and it would have worked the same. That example may be a little bit weird.Let’s do another example.
will output:
Ruby on Rails does something similar (but quite more complex) with
before_filter, and it makes sure that all callbacks you define with it are called before your normal controller methods.I hope this clears things a little bit for you.