@person.foo # method name is foo
@person.baaz # method name is baaz
I have a need to pass the name of the attribute and not the value of
the attribute
def process(input)
puts input
end
process(@person.foo) # result should be ‘foo’ and not the value of foo
how do I pass the value ‘foo’ the attribute name and not the value of
attribute to another method.
Any help?
Perhaps some context would be helpful in this case, but short of that I
am
assuming you want to invoke the named method later.
You can either pass around the symbols as method names (:foo or :baaz in
your case) and later use send()
e.g
class A
def hello
puts “hello”
end
end
a = A.new
a.send :hello # send message to the object
or alternatively you can use the Method object like
m = a.method(:hello)
m.call
HTH
Hi,
On 3/25/07, Neeraj K. [email protected] wrote:
puts input
end
process(@person.foo) # result should be ‘foo’ and not the value of foo
how do I pass the value ‘foo’ the attribute name and not the value of
attribute to another method.
Any help?
Are you looking for something like this?
module Kernel
private
def this_method_name
caller[0] =~ /`([^‘]*)’/ and $1
end
end
class Foo
def bar
this_method_name
end
def baaz
this_method_name
end
end
puts Foo.new.bar # => bar
puts Foo.new.baaz # => baaz
HTH,
Michael G.
I do not think you are going to be able to use the API you are
thinking about.
You are going to have to generate the string before you call the
method as in:
@foo.bar(“user.age”)
That is why all the association methods take symbols not references.
Ruby does not allow you to change the semantics of the calling
expression.
Michael
Sorry I should have been much clearer.
The context is that I need the name of the column for the given
attribute
Person table has name,email and age.
class Foo
def bar(input)
#not sure what goes on here
end
end
Now
@user = User.new
@foo = Foo.new
@foo.bar(@user.age or some form or it) # output shoud the column name
‘age’
Thanks.
So if I understand you right then you are probably trying to map the
value
of the column back to the column name.
eg.If you have a table like
id, name, age
1, “Alice”, 25
2, “Bob” , 35
Then given row for id 2, if you have a Fixnum 35 you want to be able to
get
string “age”. Is that right?
I am not a Rails expert but you could perhaps use column_names method on
AR.
your bar could look like
def bar(active_record, value)
active_record.attribute_names.each do |x|
return active_record.column_for_attribute(x).name if
active_record[x]
== value
end
end
and call it with bar(@user, @user.age) as in your example.
There is a big caveat though and that is since we are comparing values
there
could be more than one column of the same value and this snippet matches
the
first match.
Without going into specifics of what you need you should perhaps look
for
some alternate approach which could come from your domain use case.