views:

56

answers:

2

Lets say we have some basic AR model.

class User < ActiveRecord::Base
  attr_accessible :firstname, :lastname, :email
end

...

some_helper_method(attrib)
  ...
def  

Now I would like to pass someuser.firstname to helper and I would like to get both the value and the attribute name, for example:

some_helper_method(someuser.firstname)
> "firstname: Joe" 

some_helper_method(someuser.lastname)
> "lastname: Doe" 
+1  A: 

I am not sure what you are trying to do but here is a possible solution:

def some_helper_method(object, attr)
  "#{attr}: #{object.send(attr)}"
end

Now you can call the helper as follows:

some_helper_method(someuser, :firstname)
# => "firstname: Joe"
KandadaBoggu
Great, this method is good enough to solve the problem!
mdrozdziel
A: 

You can't do the way described in your question. For one simple reason : someuser.lastname returns a string, which is the last name.
But you don't know where this string comes from. You can't know it's the last name.

One solution would be to do the following helper method :

def some_helper_method(user, attribute)
    "#{attribute.to_s}: #{user.send(attribute)}"
end

Then you call this method with the following :

some_helper_method someuser, :lastname

The method will call someuser.lastname and return the attribute's name and it's value.

Damien MATHIEU