[rspec-users] RSpec get model attribute values by name

Pat Maddox pergesu at gmail.com
Sat Jan 31 11:37:08 EST 2009

On Sat, Jan 31, 2009 at 6:18 AM, James Byrne <lists at ruby-forum.com> wrote:
> Pat Maddox wrote:
>> I realize you didn't ask for all of that but I'm feeling a bit chatty.
>> Pat
> The more information the better. I never really did understand exactly
> what using eval() was supposed to accomplish, now I do.  Chat away...
> I do want to point out that this is what the ActiveRecord::Base api has
> to say about the [] method:
> [](attr_name)
> Returns the value of the attribute identified by attr_name after it has
> been typecast (for example, "2004-12-12" in a data column is cast to a
> date object, like Date.new(2004, 12, 12)). (Alias for the protected
> read_attribute method).
> Notice anything wrong about the api call description? Should not this
> say:
> [attr_name]

Not quite...

You must be looking at the rdoc.  RDoc looks at the method definition,
and then includes any comments above it.  Method definitions in ruby
are of the form
method_name(param1, param2, *other_params, &block)

and [] is just a method call.  You can define it on your own objects with
def [](element) .... end

Note that you can do
{:foo => "abc", :bar => "123"}.send :[], :foo

I just looked at the RDoc, and yeah you're right that it shows it of
the form [](attr_name).  That's because RDoc just sticks in the method
as it's defined.  You would need to know that this is a special case
in Ruby where you really call it like blah[:foo]


More information about the rspec-users mailing list