I want to be able to write a code like below:
MyModule::MyClass.configure do |item|
item.var1 = 'dsads'
item.var2 = 'dsadsa'
item.var3 = 'fdsfdsfd'
end
Well, I define a module and a class within it:
module MyModule
class MyClass
end
end
…and what should I do further?
If you want to do configuration, then I would recommend that you use a
Singletonclass, like this:Then you will need to define the
configuremethod on this:yieldwill evaluate the block within the context of the class, meaning that any methods called on the block object will be called on the class object.Then for each method you call inside the
configureblock, you will need a corresponding method definition inside the class. You can do this by defining the methods manually:Or, you can use
attr_accessor:To get the values back out, just do this:
If you don’t want to use a singleton, then change the class represented
MyClassto be a module instead.