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.

Pingback: Sharing my code | Pablo's new site
Pingback: Sharing my code | Pablo's new site
This is now a gem