【发布时间】: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