[rspec-users] RSpec get model attribute values by name
zach.dennis at gmail.com
Fri Jan 30 16:07:47 EST 2009
On Fri, Jan 30, 2009 at 3:45 PM, James Byrne <lists at ruby-forum.com> wrote:
> This is a request for a programming technique:
> class Mymodel < ActiveRecord::Base
> my_instance = Mymodel.new
> If I am given a string representation of an attribute "xxx" what is the
> most elegant way of passing that string to my_instance to retrieve its
> value? This is probably a common idiom, given what Rails does, but I
> cannot seem to find its code in the rails gem at the moment.
> So, if anyone knows hoe to do this off the cuff I would appreciate it.
> An example of the intended use of this is
> def table_compare(table1, table2, array_of_attributes) do |t1, t2,
> tint = t1.column_names & t2.column_names
> tfin = tint & aon
> tfin.each do |column|
> return false if t1.column <> t2.column
> return tfin #could be nil
> I want to convert the string value of the column variable into the
> attribute name to obtain the value of that attribute.
I'm assuming you want to treat your model instance like a hash:
m = MyModel.new :name => "foo"
m["name"] # => "foo"
On a different note, how about some better variable names?
More information about the rspec-users