Kevin Marsh

Bracket accessors for your Rails models

Here's an interesting hack. Tag this on the end of enviroment.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.

Others' Comments

  1. shemales stories said on January 31, 2007 @ 06:57 PM:

    Superb! (I wrote something else and then I read below that I aint supposed ter. So I deleted it.)

Your Comments

Your name:

Your email:

Your blog:

Your comment: