[rspec-users] RSpec get model attribute values by name
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"
>> 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
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.
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
I realize you didn't ask for all of that but I'm feeling a bit chatty.
More information about the rspec-users