3

I was doing the excercises in Agile Rails book and there is a private method inside application_controller.rb which is defined as:

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

This method can be called from inside UserController#index(method) but I cannot call it like:

class UserController < ApplicationController 
  @cart = current_cart
  ...

why is that?

MrDanA
  • 11,489
  • 2
  • 36
  • 47
Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90
  • this is normal object orientated behaviour... the only thing where you cant access the method is from outside..! – BvuRVKyUVlViVIc7 Nov 27 '12 at 16:52
  • @Lichtamberg but I can access the `current_cart` method from the `index` method of `UserController` class. – Alexander Suraphel Nov 27 '12 at 16:59
  • `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 Nov 27 '12 at 17:12
  • 2
    Source that @MrYoshiji forgot to cite: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility – Thilo Nov 27 '12 at 17:20

1 Answers1

6

The method you define in ApplicationController is an instance method. As such, it can be called from within another instance method of a derived controller. Here:

class UserController < ApplicationController 
  @cart = current_cart

you are attempting to call it in the class definition, not in an instance method of the class, so it's looking for a class method, which doesn't exist.

As for being able to call a private method in a derived controller, see for example Protected and private methods in Rails.

EDIT: From http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility:

In Ruby, “private” visibility is similar to what “protected” is in Java. Private methods in Ruby are accessible from children. You can’t have truly private methods in Ruby; you can’t completely hide a method.

Community
  • 1
  • 1
Thilo
  • 17,565
  • 5
  • 68
  • 84