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
103 104 105 |
# File 'lib/parametric/struct.rb', line 103 def __class_name(key) key.to_s.split('_').map(&:capitalize).join.sub(PLURAL_END, '') end |
#build(attrs) ⇒ Object
82 83 84 85 86 |
# File 'lib/parametric/struct.rb', line 82 def build(attrs) attrs.each_with_object({}) do |(k, v), obj| obj[k] = wrap(k, v) end end |
#new!(attrs = {}) ⇒ Object
53 54 55 56 57 |
# File 'lib/parametric/struct.rb', line 53 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
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/parametric/struct.rb', line 60 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
88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/parametric/struct.rb', line 88 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 |