在模块中设置新的类变量

时间:2010-05-25 20:23:14

标签: ruby class-variables

我有一个我一直在努力的插件,它将发布添加到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

关于如何将选项传递给可发布并将它们作为类变量提供的任何想法?

1 个答案:

答案 0 :(得分:16)

我假设您每班需要一套publishing_options。在这种情况下,您只想在变量前加上一个@。请记住,类本身是类Class的实例,因此当您处于类方法的上下文中时,实际上您希望在类上设置实例变量。如下所示:

module Publishable
  module ClassMethods
    def publishable(options)
      @publishing_options = options
    end

    def publishing_options
      @publishing_options
    end
  end

  def self.included(base)
    base.extend(ClassMethods)
  end
end

然后,如果ActiveRecord :: Base扩展如下:

ActiveRecord::Base.send :include, Publishable

你可以这样做:

class Note < ActiveRecord::Base
  publishable :related_attributes => [:taggings]
end

class Other < ActiveRecord::Base
  publishable :related_attributes => [:other]
end

Note.publishing_options
=> {:related_attributes=>[:taggings]}

Other.publishing_options
=> {:related_attributes=>[:other]}