如何根据其名称动态调用方法? [英] How to call methods dynamically based on their name?

查看:50
本文介绍了如何根据其名称动态调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当名称包含在字符串变量中时,如何动态调用方法?例如:

How can I call a method dynamically when its name is contained in a string variable? For example:

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`.

我该怎么做?这样做有安全隐患吗?

How can I do this? Is doing so a security risk?

推荐答案

您要执行的操作称为动态派遣.在Ruby中非常简单,只需使用 public_send :

What you want to do is called dynamic dispatch. It’s very easy in Ruby, just use public_send:

method_name = 'foobar'
obj.public_send(method_name) if obj.respond_to? method_name

如果该方法是私有/受保护的,请使用 send 代替,但更喜欢public_send.

If the method is private/protected, use send instead, but prefer public_send.

如果method_name的值来自用户,则存在潜在的安全风险.为防止漏洞,您应该验证可以实际调用的方法.例如:

This is a potential security risk if the value of method_name comes from the user. To prevent vulnerabilities, you should validate which methods can be actually called. For example:

if obj.respond_to?(method_name) && %w[foo bar].include?(method_name)
  obj.send(method_name)
end

这篇关于如何根据其名称动态调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆