Refactoring the controller instance variable finds

I hope this is the right kind of question to ask here; I can’t find any info on this specific question, but I am not sure what to search on.

Is there a best practice around how to write the much-duplicated ‘find’ in the controller?

Here are a couple standard methods:

def show
  @object = Object.find(params[:id])
  ...
  respond_with @object
end

def edit
  @object = Object.find(params[:id])
  ...
  respond_with @object
end

I’ve seen this moved to a before_filter like this:

before_filter :find_object, only: [:show, :edit]
...
def show
  ...
  respond_with @object
end

def edit
  ...
  respond_with @object
end
...
private
def find_object
  @object = Object.find(params[:id])
end

And also calling the method directly, setting the @var the first time, and just referencing it from then on:

def show
  ...
  respond_with object
end

def edit
  ...
  respond_with object
end
...
private
def object
  @object ||= Object.find(params[:id])
end

Is there any preference of what works best? Any downside to either of these methods? I find both refactorings to be kind of more confusing than helpful, but if something is common practice, OR if one is just a better way to write the code, it’ll just be a matter of getting used to it going forward.

Personally I prefer to be very explicit and have the duplication in each action. On occasion I have gone with the 2nd refactoring, but I don’t love it.

Setting a before filter I don’t like at all, since it might be very misleading for a coworkers that needs to use your code and goes directly to the action. He’ll have to wonder what is happening, and after he realizes the find must be happening somewhere else, he’ll have to look for it.

You may consider to use inherited_resources. Very useful to clean controllers.