Roman Le Negrate has written an excellent Rails plugin called meantime_filter.
In your Rails controllers, if you find yourself doing this for half of your actions you know something isn’t right:
def list
@note = note = Note.find(:all,
:conditions => ["user_id = ?", params[:user_id]])
end
You know you’ve been sitting there thinking “This isn’t DRYish”. Now I made this particularly simple to show the point, but it’s ugly any way you slice it as you get more complicated methods in your controllers.
The around filter is the standard way to handle this but it doesn’t work very cleanly with with_scope blocks.
meantime_filter to the rescue.
Install it by:
cd <railsproject> cd vendor/plugins wget http://roman2k.free.fr/rails/meantime_filter/0.1.1/\ plugin/meantime_filter-0.1.1.tar.gz tar -xzvf meantime_filter-0.1.1.tar.gz rm meantime_filter-0.1.1.tar.gz
Now you can do:
class NoteController < ApplicationController
meantime_filter :restrict_note_to_user
def list
@note = Note.find(:all)
end
private
def restrict_note_to_user
Note.with_scope(:find =>
{:conditions =>
["user_id = ?", session[:user_id]]}) do
yield
end
end
end
]]>