Module: TriggerSwitchD::SwitchFactory

Defined in:
lib/trigger_switch_d/switch.rb

Class Method Summary collapse

Class Method Details

.new(values) ⇒ Object

Creates the Switch class dynamically from values, which is assumed to be an Array of attributes/keys



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/trigger_switch_d/switch.rb', line 22

def self.new(values)
  definition = <<-EOS
  class Switch
    attr_reader #{values.map {|name| ":#{name}"}.join(",")}
    def initialize(value)
      value.each_pair do |key,value|
        instance_variable_set("@"+key.to_s,value) if respond_to?(key)
      end
    end
    
    def to_a_by_keys(keys)
      keys.map do |key|
        send(key)
      end
    end
  end
  EOS
  ::TriggerSwitchD.module_eval(definition)
  ::TriggerSwitchD.const_get("Switch")
end