从 Ruby 中的实例方法调用受保护的类方法 [英] Calling protected class method from instance method in Ruby

查看:42
本文介绍了从 Ruby 中的实例方法调用受保护的类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直有这个烦人的重复主题;只是说,我有一个定义实例方法和受保护类方法的类.实例方法必须调用类方法.为此,我必须打破可见性规则并使用危险的发送"功能.像这样:

I've been having this bothering recurring theme; let's just say, I have a class which defines an instance method and a protected class method. The instance method must call the class method. In order to do so, I kind of have to break the visibility rule and use the dangerous 'send' function. Something like this:

class Bang
    def instance_bang
      self.class.send(:class_band)
    end

    protected
    def self.class_bang
      puts "bang"
    end
end

我觉得这很糟糕,因为类方法应该在类范围内使用,因此应该在其中保持可见和可调用,对吗?是否有其他方法可以在需要依赖发送"函数的实例方法中使用类方法,从而不会破坏可见性?

I find this awful, since the class method should be used inside the class scope, therefore should remain visible and callable within it, right? Is there an alternative way to use class methods in instance methods with needing to rely on the "send" function and therefore not break visibility?

更新:

在 Sergio Tulentsev 的回复之后(感谢更正),我将更新我的关注点,用一个代码片段总结我对方法可见性的关注点,同时仍在定义它的范围内.

Following Sergio Tulentsev's response (thx for the correction), I'll update my concern with a code snippet that sums up my concerns of the method visibility being taken into account while still inside the scope where it has been defined.

class Bang
  def instance_bang
    private_bang = 1
    self.private_bang(private_bang)
  end
  private
  def private_bang(p)
    puts "bang"
    p
  end
end

调用 Bang.new.instance_bang 将引发异常,除非您在该 private_bang 调用上使用 send(这次我检查了它:)).

Calling Bang.new.instance_bang will raise an Exception unless you use send on that private_bang call (this time I checked it :) ).

推荐答案

回答更新的问题

禁止使用显式接收者调用私有方法.您要么必须使用隐式接收器(private_bang,没有 self)或使用 send.请参阅我的另一个答案了解更多信息.

Answering the updated question

It is forbidden to call private methods with explicit receiver. You either have to use implicit receiver (private_bang, without self) or use send. Please see my another answer for more information.

顺便说一下,原来的问题是关于从实例方法调用类实例方法.你的澄清不包括这一点.但如果仍然如此,您必须使用 self.class.send 或将方法设为公开(以便您可以使用显式接收器).

By the way, the original question is about calling class instance methods from instance methods. Your clarification doesn't include that. But if that's still true, you have to use self.class.send or make the method public (so that you can use explicit receiver).

这篇关于从 Ruby 中的实例方法调用受保护的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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