Module: ZMQMachine::ConfigClassMaker::MethodMaker

Defined in:
lib/zm/configuration.rb

Class Method Summary collapse

Class Method Details

.create_accessors(mod, fields) ⇒ Object

Helper to create some accessor methods. We have a standard one where it returns the value with no arg, or sets the value with an arg. Then we create a second method with the explicit ‘=’ on it to allow directly setting the value.

This let’s us do nice things like eval a block and set the instance vars. e.g.

SomeClass.new do
  field1 'set to this string'
end

or

some_class = SomeClass.new
some_class.field1 = 'set to this string'
puts some_class.field1 # => set to this string

or

some_class = SomeClass.new
some_class.field1('set to this string')
puts some_class.field1 # => set to this string


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/zm/configuration.rb', line 29

def self.create_accessors(mod, fields)
  fields.each do |field_name|
    code = <<-code
    def #{ field_name } (value = nil)
      if value
        @#{field_name} = value
      else
        @#{field_name}
      end
    end

    def #{ field_name }=(value)
      @#{field_name} = value
    end
    code

    mod.class_eval code
  end
end