如何调用存储在变量中的类方法

时间:2013-03-05 12:54:47

标签: ruby class-method

如果我想调用类方法(rails中的邮件程序方法),请在变量中提供其名称。我怎样才能做到这一点?对于对象,我们可以使用send,或者我们可以使用read_attribute来读取某些值

my_object.send("#{self.action_type(self)}")
my_object.read_attribute("#{self.action_type}_email") 

但对于类名,没有任何工作,因为send被定义为对象类中的实例方法。我想要这样的东西,这不会起作用,因为send无法在课堂上应用:

Notifier.send("#{self.action_type(self)}").deliver

4 个答案:

答案 0 :(得分:3)

使用eval

eval("Notifier.#{self.action_type}(self).deliver")

不安全但它应该有效。

答案 1 :(得分:2)

你也可以这样做:

method = Notifier.method(action_type)
method.call(self).deliver

答案 2 :(得分:2)

类是对象。申请send的方式没有区别。

Notifier.send(action_type, self).deliver

答案 3 :(得分:0)

您也可以使用

self.class.send(:your_class_method)