Setting new class variables inside a module

I have a plugin that I worked on that adds publication to ActiveRecord classes. I am expanding my classes using my publisher as follows:

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

My publisher is structured as:

 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 parameters for publication and have them as a class variable?

+4
source share
1 answer

I assume you need one set of publishing_options for each class. In this case, you just want to prefix your variable with one @ . Remember that the class itself is an instance of the Class class, so when you are in the context of a class method, you really want to set the instance variable in your class. Something like the following:

 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 

Then, if ActiveRecord :: Base expands as follows:

 ActiveRecord::Base.send :include, Publishable 

You can do:

 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]} 
+16
source

Source: https://habr.com/ru/post/1310904/


All Articles