简体   繁体   中英

Calling a method of a Rails Engine from Main App

I have a Rails engine and have the following in the {Rails_engine}/lib/role_authorization/session_user.rb

  module RoleAuthorization
        class SessionUser
          mattr_accessor :current_user, :role

        def current_user(user)
          current_user = user
        end

        def roles(role)
          role = roles
        end      
       end
      end

I am calling the following methods from the main_application {main_app}/errors/application_errors.rb

class ApplicationErrors

    def self.access_denied error, controller

     RoleAuthorization::SessionUser.current_user(current_user)

    end

However i am getting an undefined method current_user here . Does anybody have any idea what i am doing here

RoleAuthorization::SessionUser.current_user

Is undefined because you defined current_user as an instance method on the SessionUser class. Without knowing exactly how you're using this class in the rest of the system these following suggestions could work but break something else:

RoleAuthorization::SessionUser.new.current_user(current_user)

or add self to the method declaration in SessionUser:

module RoleAuthorization
  class SessionUser
    class << self
      attr_accessor :current_user, :role

      def current_user(user = nil)
        self.current_user ||= user
      end
    end
  end
end

Notice I changed mattr_accessor to attr_accessor . This is because the former is for Modules only and you're calling it within a class. Then I open up the singleton class with class << self so I can define current_user as a class method and use attr_accessor to access class instance variables. Assigning user to self.current_user will now make it available for access via: RoleAuthorization::SessionUser.current_user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM