Pat M. wrote:
I’m curious, why not just call fetch_collections at the beginning of
the method? For me that would just make more sense because I can look
at the method and know exactly what’s happening, whereas I might
forget to check to see if there’s a before_filter. I’d like to avoid
any confusion at all.
If you only call the method one time then it makes sense to add that
method call at the top of your
action method. The OP was asking how-to makes things in a more DRY
manner. Marcel’s suggestion does
this because the OP is now shown a better way to write code for reuse.
Also, I just wanted to know if there’s any difference at all between
using before_filter and just calling the method at the beginning.
Probably not, but just wanted to be sure.
before_filters are executed before your action method is called. If a
before_filter returns false it
will not continue on to call the action method. This can be ideal for
any precondition to an action.
A good example is user authorization. You can enforce users are
authorized before accessing
certain actions, and you can do it on one line! This makes it less
error-prone then adding a call to
“authorize” at the beginning of every action, because you’re reducing
the # of repeated lines you
have to maintain.
Would you prefer?
before_filter :authorize, :only=>[ :status, :admin ]
I prefer the first…