player
对象响应属性 - 我想返回属性的名称(例如uid
,external_uid
,消息字符串中的name
,birth_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
有没有办法插入属性的名称?
答案 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