如何从子模块访问属性

时间:2014-06-30 19:30:21

标签: ruby-on-rails ruby

所以我正在为RoR应用程序进行一种自定义滚动历史记录跟踪。我挂断的部分是获取登录用户信息以与记录绑定。我想通过一个附加到ActionController::Base类的子模块来获取用户。问题是,我在从子模块中检索它时遇到了麻烦。

这是我的代码:

module Trackable


  # This is the submodule
  module TrackableExtension

    extend ActiveSupport::Concern
    attr_accessor :user

    included do
      before_filter :get_user
    end

    def get_user
      @user ||= current_user # if I log this, it is indeed a User object
    end
  end




  # Automatically call track changes when 
  # a model is saved
  extend ActiveSupport::Concern
  included do 
    after_update :track_changes
    after_destroy :track_destroy
    after_create :track_create
    has_many :lead_histories, :as => :historical
  end


  ### ---------------------------------------------------------------
  ### Tracking Methods

  def track_changes
    self.changes.keys.each do |key|
      next if %w(created_at updated_at id).include?(key)

      history = LeadHistory.new
      history.changed_column_name = key
      history.previous_value = self.changes[key][0]
      history.new_value = self.changes[key][1]
      history.historical_type = self.class.to_s
      history.historical_id = self.id
      history.task_committed = change_task_committed(history)
      history.lead = self.lead

      # Here is where are trying to access that user.
      # @user is nil, how can I fix that??
      history.user = @user

      history.save
    end
  end

在我的模型中,它很简单:

class Lead < ActiveRecord::Base
    include Trackable
    # other stuff
end

1 个答案:

答案 0 :(得分:0)

我通过设置Trackable模块变量来实现这一点。

在我的TrackableExtension::get_user方法中,我执行以下操作:

def get_user
    ::Trackable._user = current_user #current_user is the ActionController::Base method I have implemented
end

然后对于我添加的Trackable模块:

class << self
    def _user
        @_user
    end

    def _user=(user)
        @_user = user
    end
end

然后,在任何Trackable方法中,我都可以执行Trackable::_user并获得正确的值。