当方法的名称包含在字符串变量中时,如何动态调用该方法?例如:
class MyClass
def foo; end
def bar; end
end
obj = MyClass.new
str = get_data_from_user # e.g. `gets`, `params`, DB access, etc.
str #=> "foo"
# somehow call `foo` on `obj` using the value in `str`.
我怎样才能做到这一点?这样做是否存在安全风险?
你想做的事情叫做动态调度 https://en.wikipedia.org/wiki/Dynamic_dispatch。在 Ruby 中非常简单,只需使用public_send http://ruby-doc.org/core/Object.html#method-i-public_send:
method_name = 'foobar'
obj.public_send(method_name) if obj.respond_to? method_name
如果该方法是私有/受保护的,请使用send http://ruby-doc.org/core/Object.html#method-i-send相反,但更喜欢public_send
.
如果值method_name
来自用户。为了防止漏洞,您应该验证哪些方法可以实际调用。例如:
if obj.respond_to?(method_name) && %w[foo bar].include?(method_name)
obj.send(method_name)
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)