Module: Paradocs::Struct::ClassMethods

Defined in:
lib/paradocs/struct.rb

Instance Method Summary collapse

Instance Method Details

#build(attrs) ⇒ Object



67
68
69
70
71
# File 'lib/paradocs/struct.rb', line 67

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

#new!(attrs = {}, environment = {}) ⇒ Object

Raises:



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

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

#paradocs_after_define_schema(schema) ⇒ Object

this hook is called after schema definition in DSL module



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

def paradocs_after_define_schema(schema)
  schema.fields.keys.each do |key|
    key = schema.fields[key].[:alias] || key
    define_method key do
      _graph[key]
    end
  end
end

#paradocs_build_class_for_child(key, child_schema) ⇒ Object



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

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

#wrap(key, value) ⇒ Object



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

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?(Paradocs::Schema)
      klass = paradocs_build_class_for_child(key, cons)
      klass.paradocs_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