【问题标题】:Why can method defined as private on ApplicationController be called inside methods of derived class but not inside the derived class itself?为什么在 ApplicationController 上定义为私有的方法可以在派生类的方法内部调用,但不能在派生类本身内部调用?
【发布时间】:2012-11-15 08:35:42
【问题描述】:

我在敏捷 Rails 书中做练习,application_controller.rb 中有一个私有方法,定义为:

private 
  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound 
    cart = Cart.create session[:cart_id] =  cart.id cart 
  end

这个方法可以从 UserController#index(method) 内部调用,但我不能这样称呼它:

class UserController < ApplicationController 
  @cart = current_cart
  ...

这是为什么呢?

【问题讨论】:

  • 这是正常的面向对象的行为......您无法访问该方法的唯一事情是从外部......!
  • @Lichtamberg 但我可以从index 类的index 方法访问current_cart 方法。
  • The difference between protected and private is subtle. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object---it is never possible to access another object instance's private methods directly, even if the object is of the same class as the caller. For protected methods, they are accessible from objects of the same class (or children).
  • @MrYoshiji 忘记引用的来源:en.wikibooks.org/wiki/Ruby_Programming/Syntax/…

标签: ruby-on-rails ruby ruby-on-rails-3 oop


【解决方案1】:

你在ApplicationController中定义的方法是一个实例方法。因此,它可以从派生控制器的另一个实例方法中调用。这里:

class UserController < ApplicationController 
  @cart = current_cart

你试图在类定义中调用它,而不是在类的实例方法中,所以它正在寻找一个不存在的类方法。

至于能否在派生控制器中调用私有方法,请参见例如Protected and private methods in Rails

编辑:来自http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility

在 Ruby 中,“私有”可见性类似于 Java 中的“受保护”可见性。 Ruby 中的私有方法可以从子级访问。你不能在 Ruby 中拥有真正的私有方法;你不能完全隐藏一个方法。

【讨论】:

  • 伟大的@Thilo。我想知道在类定义中调用方法时 ruby​​ 的行为是什么。它是否寻找类方法?
猜你喜欢
  • 1970-01-01
  • 2013-12-26
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 2015-01-04
  • 2013-10-08
  • 1970-01-01
相关资源
最近更新 更多