Before_filter symbol with params


#1

I had a need to do something like:

before_filter :require_permissions, :slot => :forums, :only => :edit

where I wanted require_permissions to be able to access the non-filter-
config-related hash params. However, unlike custom model validators,
on spelunking into the rails controller filter code it appears the
config hash params aren’t available to the filter method when declared
this way – not even the non-filter-specific (e.g. :slot) params.

I did something like what dblack has suggested elsewhere on this forum
ala:

before_filter Proc.new { |controller|
controller.send(:require_permissions, :forums) }, :only => :edit

which should be analogous to:

before_filter :only => :edit { |controller|
controller.send(:require_permissions, :forums) }

Things that bum me out about this:

  • require_permissions is protected (which it should be, so it’s not a
    public action that could incorrectly be called by a web request) so
    you can’t just do controller.require_permissions(:forums) in the
    block, so I had to directly monkey the method-hiding by calling
    controller.send.

  • what could be nice and concise (the first version of what I wanted)
    becomes much longer and more verbose.

This would seem like a common pattern lots of folks might want, to
make it easy to use a symbol when specifying a filter while still
specifying some options, just like the model validators where you can
do, for instance (lifted from some dotsrc.org code):

def self.validates_url(*attr_names)
conf = { :message => “is not a well-formed URL”,
:on => :save,
:allow_nil => false,
:schemes => [‘http’, ‘https’, ‘ftp’] }
conf.update(attr_names.pop) if attr_names.last.is_a?(Hash)
[…]
end

where you see custom params such as :schemes that they can do with
what they will.

Is there a better way?


Walter Korman – http://lemurware.blogspot.com