using a block.
A key difference with using the block form is that (because blocks are
closures) self will be the class, not the controller instance (which
is why you get passed the controller as a parameter). For example you
can’t do
because that will set the instance variable in the wrong object. you
could use controller.instance_variable_set but that’s just disgusting.
so you’re left with
before_filter do |controller|
controller.some_method
end
…
def some_method
end
at which point you might as well do before_filter :some_method. Plus I
like giving things names when appropriate.
because that will set the instance variable in the wrong object. you
could use controller.instance_variable_set but that’s just disgusting.
Well now, hold on there a minute, Fred. I kind of like it. In
fact, it’s exactly what I asked for. I don’t find it all that
disgusting. Anyway, I now know how to do it both ways and I can
decide which way I like the better. Thanks to all for the input in
this topic.
So, I see that we have a working solution to this problem. THAT’S
GREAT NEWS! Thanks a batch for all of the contributions.
I would, however, like to see if the solution couldn’t be advanced one
step further. The methodology that we have working so far is to
define a method as a filter somewhere and then pass the name of that
method as a symbol to before_filter. Obviously, this requires a
separate definition of the method. My question is this: Can we
somehow do this whole thing in a single step by passing the
before_filter a block rather than a symbol? before_filter is supposed
to accept a block. So, conceptually, my understanding is that we
would need some code that looks something like this:
before_filter do |controller|
some_code_here
end
Can anyone please tell me what code I would need to supply as a
replacement for some_code_here in order to get this thing to work
using a block.
because that will set the instance variable in the wrong object. you
could use controller.instance_variable_set but that’s just disgusting.
Well now, hold on there a minute, Fred. I kind of like it. In
fact, it’s exactly what I asked for. I don’t find it all that
disgusting. Anyway, I now know how to do it both ways and I can
decide which way I like the better. Thanks to all for the input in
this topic.
... doug
If you want to be a good Rails citizen, I’d recommend following Fred’s
advice. He have you a clean and conventional solution and I guarantee
you he knows what he’s talking about. I’d have given you the same advice
if the original posting was stated slightly more clearly.