【发布时间】:2011-06-02 13:19:46
【问题描述】:
我希望能够使传递给我的类方法(可审计)的选项可用于实例方法。我正在使用模块混合类和实例方法。
显而易见的选择是使用类变量,但尝试访问它时出现错误:
在 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 现在包含解决方案)
【问题讨论】:
-
在 github 上的版本中,分配时(第 16 行)在 auditable_only_once 前面只有一个 @,但您已在此处的代码中修复了该问题。您是否使用该修复程序测试了代码?还是不行吗?
-
感谢您发现这一点,我实际上尝试了单@和双@,因此必须将较新版本的代码复制到 Gist。现已修复。
标签: ruby class-variables