I’m new to Ruby and working through some tutorials/screencasts. I’ve reached the section where they’re discusisng the before_filter callback, and it’s using some syntax that’s a little weird for me. I don’t know if it’s a feature of ruby, of if it’s some rails magic, and was hoping someone here could set me straight or point me in the right direction w/r/t the manual
This is a code fragment from the screencast I’m watching
class MachinesController < ApplicationController
#...
before_filter :login_required, :only => [:report]
#...
def index
#etc...
end
def login_required
#etc...
end
end
In the context of rails, I understand that before_filter is a callback that will fire login_required method when the report action is called. However, it’s not clear to me what it is within the context of ruby. In other languages classes typically contain methods, properties, class variables and constants defined within the braces.
However, this looks like its a function call inside the class, and some experiments have show that you can put code in your class definitions and have it called when the program runs. Is this correct? If so, are there special contextual rules for code that’s put inline into a class like that? (i.e. would the before_filter function in rails know what class it was called from) If not, what magic is rails doing here?
before_filteris a not actually a callback. It’s a class method ofActiveRecord::Basethat sets up a callback when you call it. So in this example:When the class is loaded, the method is called, and it adds
:login_requiredto the filter chain for thereportmethod.The convention for these types of calls is to drop parens, but it would work just fine (and would be more easily identifiable as a method call) if you did this: