在模块内设置新的类变量
我有一个一直在开发的插件,它添加了对 ActiveRecord 类的发布。我与发布者一起扩展我的类,如下所示:
class Note < ActiveRecord::Base
# ...
publishable :related_attributes => [:taggings]
end
我的发布者的结构如下:
module Publisher
def self.included(base)
base.send(:extend, ClassMethods)
@@publishing_options = [] # does not seem to be available
end
module ClassMethods
def publishable options={}
include InstanceMethods
@@publishing_options = options
# does not work as class_variable_set is a private method
# self.class_variable_set(:@@publishing_options, options)
# results in: uninitialized class variable @@publishing_options in Publisher::ClassMethods
puts "@@publishing_options: #{@@publishing_options.inspect}"
# ...
end
# ...
end
module InstanceMethods
# results in: uninitialized class variable @@publishing_options in Publisher::InstanceMethods
def related_attributes
@@publishing_options[:related_attributes]
end
# ...
end
end
关于如何将选项传递给可发布并将它们作为类变量使用的任何想法?
I have a plugin I have been working on that adds publishing to ActiveRecord classes. I extend my classes with my publisher like so:
class Note < ActiveRecord::Base
# ...
publishable :related_attributes => [:taggings]
end
My publisher is structured like:
module Publisher
def self.included(base)
base.send(:extend, ClassMethods)
@@publishing_options = [] # does not seem to be available
end
module ClassMethods
def publishable options={}
include InstanceMethods
@@publishing_options = options
# does not work as class_variable_set is a private method
# self.class_variable_set(:@@publishing_options, options)
# results in: uninitialized class variable @@publishing_options in Publisher::ClassMethods
puts "@@publishing_options: #{@@publishing_options.inspect}"
# ...
end
# ...
end
module InstanceMethods
# results in: uninitialized class variable @@publishing_options in Publisher::InstanceMethods
def related_attributes
@@publishing_options[:related_attributes]
end
# ...
end
end
Any ideas on how to pass options to publishable and have them available as a class variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您希望每个课程有一组
publishing_options
。在这种情况下,您只需在变量前添加一个@
前缀。请记住,类本身是类Class
的实例,因此当您处于类方法的上下文中时,您实际上想要在类上设置实例变量。如下所示:那么如果 ActiveRecord::Base 扩展如下:
您可以执行以下操作:
I am presuming that you want one set of
publishing_options
per class. In that case you just want to prefix your variable with a single@
. Remember the class itself is an instance of the classClass
so when you are in the context of a class method you actually want to set an instance variable on your class. Something like the following:Then if ActiveRecord::Base is extended as follows:
You can do: