I have a basic module that has some logic in it and is included inside different classes. Now I need a block configurethat sets up some configuration of how the class should behave.
I tried the following code:
class MyConfig
attr_accessor :foo, :bar
end
module BaseModule
def self.included base
base.include InstanceMethods
base.extend ClassMethods
end
module ClassMethods
attr_reader :config
def configure &block
@config = MyConfig.new
block.call(@config)
end
end
module InstanceMethods
def do_something
puts self.class.config.inspect
end
end
end
class MyClass1
include BaseModule
configure do |config|
config.foo = "foo"
end
end
class MyClass2
include BaseModule
configure do |config|
config.bar = "bar"
end
end
MyClass1.new.do_something
MyClass2.new.do_something
- I'm not sure if an instance variable
@configfor a module / class is the best way to set up a class. Is this right, or are there better solutions? - Is it good to use
base.extend ClassMethodswhen the module is turned on only with include BaseModule? A developer might expect that only instance methods are included, but as a side effect there are also extended class methods.
Update
MyConfig, . , config.foo = "foo".