11 Oct 2006
Bracket accessors for your Rails models
Here’s an interesting hack. Tag this on the end of environment.rb:
module ActiveRecord
class Base
def self.[](id)
self.find(id)
end
end
end
Now you can do fun things like:
>> Person[1]
=> #<Person:0x23c7a00 @attributes={"name"=>"Alice", "id"=>"1"}>
>> Person[1].name
=> "Alice"
Which is equivalent to:
>> Person.find(1)
=> #<Person:0x23c7a00 @attributes={"name"=>"Alice", "id"=>"1"}>
>> Person.find(1).name
=> "Alice"
…but far cooler.
In other news, I really need to upgrade to Mephisto – just as soon as they add XML-RPC support.
