I think everyone get’s it by now. In rubyland, we generally like Skinny Controllers and Fat Models. I just wanted to share a little before_filter I use on my CRUD controllers to make each action smaller even if it doesn’t make the whole controller smaller.

def load_record
  unless params[:id].blank?
    @record = SomeActiveRecordClass.find(params[:id])
  end
  if @record.nil?
    @record = SomeActiveRecordClass.new
  end
  @record.attributes = params[:record] if params[:record]
end

I run this little before filter before new, create, edit, update, and destroy. In any of those actions you can depend on @record being set in the proper state, ready for saving, populating a form, or deleting.

It isn’t anything special just a way to keep boilerplate code out of the actions themselves.

Do you have any before_filter patterns? How do you keep your controllers looking slim and trim?

On an unrelated note, RideCharge, my employer, is actively seeking a QA Specialist. Our ideal QA person would be able to write automated tests in addition to normal QA activity. If you have anymore questions contact me schlueter [at] gmail [.] com.

Post Information

Tags:

  • No Tags

We're Reading

Feeds/Syndication

3 Responses to “Clean Up Controllers with Before Filters”

Leave a Reply