无法在前置模块

时间:2017-04-29 18:53:20

标签: ruby-on-rails ruby module prepend

我希望能够在ActiveRecord :: Base中包含我的模块,以便我的Rails AR类可以使用has_folder_attachments方法。

我这样做是为了扩展原始模块的功能以支持AR挂钩;但是变量@physical_path@dice都是零,我不明白为什么。

module FolderAttachments
  module ClassMethods
    def has_folder_attachments(physical_path, excludes: [])
      @physical_path = physical_path
      super
    end 
  end  

  def self.prepended(base)
    class << base
      prepend ClassMethods
    end  
  end  

  attr_reader :physical_path
end

module ActiveRecord
  class Base
    prepend FolderAttachments

    attr_reader :dice

    # This should run after the module method
    def self.has_folder_attachments(*args)
      @dice = true
    end
  end
end

class Damned < ActiveRecord::Base
  has_folder_attachments :for_real
end

damn = Damned.new
puts damn.physical_path # => nil
puts damn.dice          # => nil

1 个答案:

答案 0 :(得分:0)

使用这两个变量时,您正在混合实例和(元)类上下文。两个变量都在类上下文中运行的方法中设置它们的值(更确切地说,在metaclass的上下文中)。因此,您无法在实例上下文中访问这些变量(及其attr_reader)。

要使attr_reader生效,您必须将它们移至类上下文并从那里访问它们:

module FolderAttachments
  module ClassMethods
    ...
    attr_reader :physical_path
  end
end

module ActiveRecord
  class Base
    ...
    class << self
      attr_reader :dice
    end
  end
end

damn = Damned.new
damn.class.physical_path # => :for_real
damn.class.dice          # => true

或者您也可以添加委托给类级读者的实例级读者,以便您也可以在实例上下文中访问它们:

module FolderAttachments
  module ClassMethods
    ...
    attr_reader :physical_path
  end

  def physical_path
    self.class.physical_path
  end
end

module ActiveRecord
  class Base
    ...
    class << self
      attr_reader :dice
    end

    def dice
     self.class.dice
    end
  end
end

damn = Damned.new
damn.physical_path # => :for_real
damn.dice          # => true