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

Pat Maddox pergesu at gmail.com
Fri Jan 30 22:00:09 EST 2009


On Fri, Jan 30, 2009 at 3:56 PM, James Byrne <lists at ruby-forum.com> wrote:
> Zach Dennis wrote:
>
>>
>> m = MyModel.new :name => "foo"
>> m["name"]      # => "foo"
>>
>> http://www.railsbrain.com/api/rails-2.2.2/doc/index.html?a=M001972&name=[]
>>
>> On a different note, how about some better variable names?
>
> That code was for demonstration purposes for this question only.
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>

a = "name"

As Zach pointed out, you can access AR instance attributes like a hash:
my_instance[a] = "foobar"
my_instance[a.to_sym] # => "foobar"

the reason you can use either a symbol or a string is because the hash
access is done with a HashWithIndifferentAccess.

A couple other things you can do...

my_instance.send(a) # => "foobar"

It's important to view method calls as sending messages to objects in
Ruby... send is a method you can use to send a message to an object,
where the method name is known only at runtime.

eval "my_instance.#{a}"

and then of course you can eval strings...so if you have a var
containing the name, you can interpolate it into another string and
eval that.

I realize you didn't ask for all of that but I'm feeling a bit chatty.

Pat


More information about the rspec-users mailing list