I think what you mean with "member variable", is that you have a model that has an attribute called first_name
. If so, then you can access that attribute as you'd do in a "plain" ("plain" because the question is focused to Rails) Ruby class:
class Foo
attr_accessor :name
def initialize(name)
@name = name
end
end
foo = Foo.new('bar')
p foo.instance_variables # [:@name]
p foo.instance_variable_get('@name') # "bar"
The most idiomatic way to get dynamically an instance variable is using instance_variable_get
, but you can also use send
, or better using __send__
, or even better in your case using public_send
:
foo = Foo.new('bar')
p foo.instance_variables # [:@name]
p foo.instance_variable_get('@name') # "bar"
p foo.send('name') # "bar"
p foo.public_send('name') # "bar"
The way Rails handles your models and attributes is almost the same (NOTE: opened to edition). By instantiating one of your models, you can get the attribute you need:
user = User.first
user.email # email@mail.com
user.public_send('email') # email@mail.com