Method: Dply::BaseConfig.new_struct_klass

Defined in:
lib/dply/base_config.rb

.new_struct_klass(opts) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/dply/base_config.rb', line 21

def self.new_struct_klass(opts)
  Class.new do

    def initialize
      @proc_map = {}
    end

    def set_proc(opt, pr)
      @proc_map[opt] = pr
      ivar = "@#{opt}"
      remove_instance_variable(ivar) if instance_variable_defined?(ivar)
    end

    opts.each do |opt, type|

      define_method "#{opt}=" do |value|
        assert_type(opt, value, type)
        instance_variable_set("@#{opt}", value)
      end

      define_method opt do
        if instance_variable_defined?("@#{opt}")
          instance_variable_get("@#{opt}")
        elsif @proc_map.key?(opt)
          value = instance_eval(&@proc_map.fetch(opt))
          public_send("#{opt}=", value)
        else
          instance_variable_set("@#{opt}", nil)
        end
      end
    end

    opts = nil

    private def assert_type(opt, value, type)
      if not value.is_a?(type)
        raise Error, "opt(#{opt}) has value '#{value}' of type '#{value.class}' (Expected: '#{type}')"
      end
    end
  end
end