【问题标题】:How come methods under 'private' and 'protected' can always be called in models (rails)?为什么总是可以在模型(rails)中调用“私有”和“受保护”下的方法?
【发布时间】:2016-04-20 13:55:55
【问题描述】:

我测试过,它们实际上不起作用:

class User < ActiveRecord::Base

  def self.call_protected_method
    protected_method
  end

  def self.call_private_method
    private_method
  end

  protected

  def self.protected_method
    puts "protected_method"
  end

  private

  def self.private_method
    puts "private_method"
  end

end

我的意思是,它们不起作用,是您可以调用此示例中的所有方法。它们是否处于私有和/或受保护状态并不重要。

# in rails console:
User.call_protected_method # => protected_method
User.protected_method      # => protected_method
User.call_private_method   # => private_method
User.private_method        # => private_method

这是为什么呢?忽略“私有”和“受保护”的原因是什么?

更新:我的问题不是如何做到这一点。我的问题是为什么这种方法在 Rails 模型中不起作用!?

【问题讨论】:

  • 你预期会发生什么,结果发生了什么?
  • 我的意思是,它们不起作用,是您可以调用此示例中的所有方法。它们是否处于私有和/或受保护状态并不重要。这是为什么?这是什么原因?

标签: ruby-on-rails activemodel


【解决方案1】:

您正在尝试定义一个私有类方法,而这不适用于该语法。你要private_class_method

也看看这些答案:Ruby class with static method calling a private method?

【讨论】:

  • 我的问题不是如何做到这一点。我的问题是为什么这种方法在 Rails 模型中不起作用!?
  • Rails 与它无关,它是 ruby​​ 语言功能。这篇文章可能会解释这种行为存在的原因:jakeyesbeck.com/2016/01/24/ruby-private-class-methods
猜你喜欢
  • 2011-12-05
  • 1970-01-01
  • 2011-07-09
  • 2011-01-31
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 2011-06-14
  • 2013-01-18
相关资源
最近更新 更多