我希望能够使传递给我的类方法(可审计)的选项可用于实例方法。我正在使用模块混合类和实例方法。
显而易见的选择是使用类变量,但在尝试访问它时出现错误:
Auditable 中未初始化的类变量@@auditable_only_once
class Document
include Auditable
auditable :only_once => true
end
# The mixin
module Auditable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def auditable(options = {})
options[:only_once] ||= false
class_eval do
# SET THE OPTION HERE!!
@@auditable_only_once = options[:only_once]
end
end
end
private
def audit(action)
# AND READ IT BACK LATER HERE
return if @@auditable_only_once && self.audit_item
AuditItem.create(:auditable => self, :tag => "#{self.class.to_s}_#{action}".downcase, :user => self.student)
end
end
我已经删除了一些代码以使其更易于阅读,完整的代码在这里:https ://gist.github.com/1004399(编辑:Gist 现在包括解决方案)