Module: Parametric::Struct::ClassMethods

Defined in:
lib/parametric/struct.rb

Instance Method Summary collapse

Instance Method Details

#build(attrs) ⇒ Object



66
67
68
69
70
# File 'lib/parametric/struct.rb', line 66

def build(attrs)
  attrs.each_with_object({}) do |(k, v), obj|
    obj[k] = wrap(k, v)
  end
end

#new!(attrs = {}) ⇒ Object

Raises:



51
52
53
54
55
# File 'lib/parametric/struct.rb', line 51

def new!(attrs = {})
  st = new(attrs)
  raise InvalidStructError.new(st) unless st.valid?
  st
end

#parametric_after_define_schema(schema) ⇒ Object

this hook is called after schema definition in DSL module



58
59
60
61
62
63
64
# File 'lib/parametric/struct.rb', line 58

def parametric_after_define_schema(schema)
  schema.fields.keys.each do |key|
    define_method key do
      _graph[key]
    end
  end
end

#parametric_build_class_for_child(key, child_schema) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/parametric/struct.rb', line 72

def parametric_build_class_for_child(key, child_schema)
  klass = Class.new do
    include Struct
  end
  klass.schema = child_schema
  klass
end

#wrap(key, value) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/parametric/struct.rb', line 80

def wrap(key, value)
  field = schema.fields[key]
  return value unless field

  case value
  when Hash
    # find constructor for field
    cons = field.[:schema]
    if cons.kind_of?(Parametric::Schema)
      klass = parametric_build_class_for_child(key, cons)
      klass.parametric_after_define_schema(cons)
      cons = klass
    end
    cons ? cons.new(value) : value.freeze
  when Array
    value.map{|v| wrap(key, v) }.freeze
  else
    value.freeze
  end
end