Module: Parametric::Struct::ClassMethods
- Defined in:
- lib/parametric/struct.rb
Constant Summary collapse
- PLURAL_END =
/s$/.freeze
Instance Method Summary collapse
- #__class_name(key) ⇒ Object
- #build(attrs) ⇒ Object
- #new!(attrs = {}) ⇒ Object
-
#parametric_after_define_schema(schema) ⇒ Object
this hook is called after schema definition in DSL module.
- #wrap(key, value) ⇒ Object
Instance Method Details
#__class_name(key) ⇒ Object
107 108 109 |
# File 'lib/parametric/struct.rb', line 107 def __class_name(key) key.to_s.split('_').map(&:capitalize).join.sub(PLURAL_END, '') end |
#build(attrs) ⇒ Object
86 87 88 89 90 |
# File 'lib/parametric/struct.rb', line 86 def build(attrs) attrs.each_with_object({}) do |(k, v), obj| obj[k] = wrap(k, v) end end |
#new!(attrs = {}) ⇒ Object
57 58 59 60 61 |
# File 'lib/parametric/struct.rb', line 57 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
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/parametric/struct.rb', line 64 def parametric_after_define_schema(schema) schema.fields.values.each do |field| if field.[:schema] if field.[:schema].is_a?(Parametric::Schema) klass = Class.new do include Struct end klass.schema = field.[:schema] self.const_set(__class_name(field.key), klass) klass.parametric_after_define_schema(field.[:schema]) else self.const_set(__class_name(field.key), field.[:schema]) end end self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{field.key} _graph[:#{field.key}] end RUBY end end |
#wrap(key, value) ⇒ Object
92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/parametric/struct.rb', line 92 def wrap(key, value) case value when Hash # find constructor for field cons = self.const_get(__class_name(key)) cons ? cons.new(value) : value.freeze when Array value.map{|v| wrap(key, v) }.freeze else value.freeze end end |