开发者

How to convert attribute name to string?

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" 

s开发者_JAVA百科ome_helper_method(someuser.lastname)
> "lastname: Doe" 


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜