如何将变量的给定名称插入到字符串中?

时间:2014-04-04 09:17:36

标签: ruby

编辑:道歉,也许这还不清楚。问题不在于让player对象响应属性 - 我想返回属性的名称(例如uidexternal_uid,消息字符串中的namebirth_date等),而不是值。

我正在尝试重构一些测试,我有一个看起来像这样的方法:

 def assert_frozen(player)
    assert_predicate player.uid, :frozen?, 'uid is not frozen'
    assert_predicate player.profile.external_uid, :frozen?,
      'external_uid is not frozen'
    # etc, etc, for all of the attributes
 end

我想做类似的事情:

def assert_frozen_attribute(player_attribute)
  assert_predicate player.player_attribute, :frozen?, 'PLAYER_ATTRIBUTE is not frozen'
  # if the uid were not frozen, this should return "uid is not frozen"
end

有没有办法插入属性的名称?

2 个答案:

答案 0 :(得分:1)

您可以使用Object#public_send

assert_predicate player.public_send(player_attribute), :frozen?, "#{player_attribute} is not frozen"

答案 1 :(得分:1)

您可以这样做,您可以传递字符串'uid'或符号:uid(首选)作为属性。

def assert_frozen_attribute(player_attribute)
  assert_predicate player.send(player_attribute), :frozen?, "#{player_attribute} is not frozen"
end