Never been to TextSnippets 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!)

Simple accessor method for ActiveRecord objects (See related posts)

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]


You need to create an account or log in to post comments to this site.


Related Posts