Find or 404

There’s a pattern I use often: find a record or throw a 404. In my Rails apps that means literally throwing a 404 exception. After hard-coding that logic in my controllers countless times, I’ve decided to abstract it out and this is how it works. Instead of:

Blog.find(id)

you now do

Blog.fof.find(id)

It also works for associations:

blog = Blog.fof.find(blog_id)
post = blog.posts.fof.find(id)

Fof stands for “Find or Four oh four”. The code to accomplish that is:

class NotFound  e
    if arguments.last.is_a? Hash
      arguments = arguments[0..-2].inspect[1..-2] + ", " + arguments.last.inspect[1..-2]
    else
      arguments = arguments.inspect[1..-2]
    end
    raise NotFound.new("Not found: #{@model.name}.#{method}(#{arguments}): #{e.message}")
  end
end

class ActiveRecord::Base
  def self.fof
    @_fof ||= FOF.new(self)
  end
end

Now that I think about it, I could have called it fofof.

Update: this is now a gem.

Update: this is actually useless.

Advertisements

3 Replies to “Find or 404”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s