简体   繁体   English

从主应用程序调用Rails Engine的方法

[英]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 我有一个Rails引擎,并且在{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 我正在从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 . 但是我在这里得到一个未定义的方法current_user。 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. 未定义,因为您已将current_user定义为SessionUser类的实例方法。 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: 或将自己添加到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 . 注意,我将mattr_accessor更改为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. 然后,我用class << self打开单例类,以便可以将current_user定义为类方法,并使用attr_accessor访问类实例变量。 Assigning user to self.current_user will now make it available for access via: RoleAuthorization::SessionUser.current_user 现在,将用户分配给self.current_user将使其可通过以下方式访问: RoleAuthorization::SessionUser.current_user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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