2

I am troubleshooting why my ApplicationController's methods don't seem to work in my namespaced admin area and it seems like when I'm in a namespace I cannot access my ApplicationController's private methods, is this right?

If it is like that, what's the best practise to reuse something like Authlogic's example ApplicationController methods in my namespaced controller? I could easily copy and paste the methods to an AdminController or something, and I could also un-private these methods - but this doesn't seem like such a good way to do it.

Here's what the example ApplicationController from Authlogic (and mine) looks like:

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user_session, :current_user

  private
    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.user
    end  

    def require_user
      unless current_user
        store_location
        flash[:notice] = "You must be logged in to access this page"
        redirect_to new_user_session_url
        return false
      end
    end

    # and some more methods here...

end

And that's how I inherit from it in my namespace:

class Admin::DashboardController < ApplicationController
  layout 'administration'

  require_user # fails

  def index
  end

end

Thanks for your help,

Arne

arnekolja
  • 1,687
  • 5
  • 22
  • 29

2 Answers2

1

You should use before_filter in Admin::DashboardController:

class Admin::DashboardController < ApplicationController
  layout 'administration'

  before_filter :require_user

  def index
  end
end
Voldy
  • 12,829
  • 8
  • 51
  • 67
  • Is it a good practice to keep current_user as a public method? Are there risks associated with this? I imagine one of the popular tutorials somewhere makes them private-instead-of-public, because I found I had made this mistake, too. – Mittenchops Jul 19 '12 at 22:41
  • @Voldy you're wrong in your first point. That's not how method visibility works in ruby. That tutorial is wrong. You _can_ access a private methods from within a subclass, just try it on irb. In ruby, private means you cannot use a receiver, just access from the instance context, which includes any subclass instance context. – grzuy Oct 14 '12 at 16:50
0

I haven't used authlogic, but maybe you need to change

require_user

to

before_filter :require_user
coder_tim
  • 1,710
  • 1
  • 12
  • 13