不能调用私有类方法

Joh*_*ith 1 ruby ruby-on-rails

尝试在同一类中调用私有方法时出现以下错误:

undefined local variable or method a_private_method' 用于 AClass (NameError)`

这里的类:

class AClass
  def self.public_method
    file = a_private_method
  end

  private

  def a_private_method
    do something
  end
end
Run Code Online (Sandbox Code Playgroud)

Chr*_*yer 8

您正在尝试从类方法调用实例方法,这当然不起作用。

尝试这个

class AClass
  class << self
    def public_method
      file = a_private_method
    end

    private

    def a_private_method
      # do something
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

您也可以self像您已经做过的那样用作接收器,但请注意,private在这种情况下,将方法移至您的类的一部分不起作用。你可以使用private_class_method

class AClass
    def self.public_method
      file = a_private_method
    end

    def self.a_private_method
      # do something
    end
    private_class_method :a_private_method
  end
end
Run Code Online (Sandbox Code Playgroud)

请参阅https://jakeyesbeck.com/2016/01/24/ruby-private-class-methodshttps://dev.to/adamlombard/ruby-class-methods-vs-instance-methods-4aje