[LRUG] Are before_filters abused in Rails?
Sam Livingston-Gray
geeksam at gmail.com
Thu Mar 22 06:42:30 PDT 2012
Using a filter ("should I perform this action?") solely for a side effect ("I need some data!") definitely seems like an abuse of the feature.
I abused filters in exactly this way for years, but now I use the load_model approach, because it (a) makes it clear that I expect a side effect and (b) doesn't require me to hold any extra context in my head. (Even if I notice the macro at the top, I don't always remember it when I get down to the action, and writing :only => [:foo] seems like more duplication. Seriously, how hard is it to just call the damn method?)
I like the helper_method approach too, but I wonder if, e.g., NewRelic might count that time as belonging to the view instead of to the controller?
--
(Sent from phone; please excuse brevity.)
On Mar 22, 2012, at 5:18 AM, mudge <mudge at mudge.name> wrote:
> Good afternoon all,
>
> I posted this on Twitter a while back but seeing as the list has been
> a flurry of activity recently, I thought I'd post it here to gather
> more debate.
>
> Do you use before_filters in your controllers to DRY up the
> instantiation of variables like so?
>
> class MyController < ApplicationController
> before_filter :load_model, :only => [:show, :edit, :update, :destroy]
>
> def show
> end
>
> def edit
> end
>
> private
>
> def load_model
> @model = Model.find(params[:id])
> end
> end
>
> It's a pattern that I've seen quite a bit and something we had taken
> to using until a member of the team began challenging it during code
> review. The gist of the issue is that he believed it to be an abuse of
> filters which should really only deal with things like authentication;
> it was his assertion that the actual loading of a model should be made
> much more explicit.
>
> The full discussion can be found at https://gist.github.com/2007669
> and I've added a few alternatives (including one inspired by the
> latest Ruby Rogues discussion about Objects in Rails
> http://rubyrogues.com/046-rr-objects-in-rails-part-2/) but I'd be keen
> to see what people here think and whether it is an issue or not.
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
More information about the Chat
mailing list