我希望能够将我的模块包含在ActivereCord ::基础中,以便我的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
使用两个变量时,您正在混合实例和(META(类上下文。这两个变量均以在类上下文中运行的方法(更准确地说是在Metaclass的上下文中(设置的值。因此,您无法在实例上下文中访问这些变量(及其attr_reader
s(。
要使attr_reader
s工作,您必须将它们移至类上下文并从那里访问它们:
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