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:
A simple addition can be made to the Role class like so:
Now the code required to retrieve a role is a lot nicer:
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]