1

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" 

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.