Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Jon Evans http://evansweb.info/

1 total

Simple accessor method for ActiveRecord objects

If you have a simple ActiveRecord object, for example 'Role', which only has a title attribute, it's a pain to have to keep looking up roles with the usual syntax:

admin_role = Role.find_by_title('admin')


A simple addition can be made to the Role class like so:

class Role < ActiveRecord::Base
  def self.[](title)
    Role.find_by_title(title.to_s)
  end
end


Now the code required to retrieve a role is a lot nicer:

admin_role = Role[:admin]

1 total