Module: ZMQMachine::ConfigClassMaker

Defined in:
lib/zm/configuration.rb

Defined Under Namespace

Modules: MethodMaker

Class Method Summary collapse

Class Method Details

.create_class(klass_name, fields, parent, mod) ⇒ Object

Dynamically generates Configuration classes. It can also create subclasses. Allows us to easily build subclasses of Configuration within the library. This functionality is also provided for users of this library to create their own Configuration classes when writing client/server programs. All of the inheritance is taken care of.

klass_name - should usually be ‘Configuration’ fields - an array of strings corresponding to the accessor names parent - the parent of this subclass (Object at the top level) mod - the module under which this subclass should be placed

module ZMQMachine

ZMQMachine::ConfigClassMaker.create_class('Configuration', %w( one two three), Object, ZMQMachine)

end

OR for a subclass

module ZMQMachine

module Server
  ZMQMachine::ConfigClassMaker.create_class('Configuration', %w( one two three), ZMQMachine::Configuration, ZMQMachine::Server)
end

end



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/zm/configuration.rb', line 74

def self.create_class(klass_name, fields, parent, mod)
    # the "here doc" usage here confuses the syntax beautifier so the indentation
    # is wrong
    klass = <<-KLASS
    #{klass_name} = Class.new(#{parent}) do

    Fields = #{fields.inspect}

    # Creates a Configuration object from another object that conforms
    # to the Configuration protocol.
    #
    def self.create_from(other_config)
      config = new
      Fields.each do |name|
        config.send(name, other_config.send(name.to_sym)) if config.respond_to?(name.to_sym)
      end
      config
    end

    def initialize(&blk)
      instance_eval(&blk) if block_given?
    end

    ZMQMachine::ConfigClassMaker::MethodMaker.create_accessors(self, Fields)
  end
  KLASS

  mod.module_eval(klass)
end