Class: TypedModel::TypeDef
- Inherits:
-
Object
- Object
- TypedModel::TypeDef
- Defined in:
- lib/typed_model/type_def.rb
Instance Attribute Summary collapse
-
#validators ⇒ Object
Returns the value of attribute validators.
-
#value_type ⇒ Object
Returns the value of attribute value_type.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(values) ⇒ TypeDef
constructor
A new instance of TypeDef.
- #to_data(value) ⇒ Object
- #typecast_value(v) ⇒ Object
- #validate(value, errors, key_prefix) ⇒ Object
Constructor Details
#initialize(values) ⇒ TypeDef
Returns a new instance of TypeDef.
51 52 53 54 |
# File 'lib/typed_model/type_def.rb', line 51 def initialize(values) @value_type = values[:type] @validators = (values[:validators] || []) end |
Instance Attribute Details
#validators ⇒ Object
Returns the value of attribute validators.
49 50 51 |
# File 'lib/typed_model/type_def.rb', line 49 def validators @validators end |
#value_type ⇒ Object
Returns the value of attribute value_type.
49 50 51 |
# File 'lib/typed_model/type_def.rb', line 49 def value_type @value_type end |
Class Method Details
.build(args) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/typed_model/type_def.rb', line 11 def build(args) spec_map = args.respond_to?(:has_key?) ? args : { type: args } t, seq_of, map_of, validations = spec_map.values_at(:type, :seq_of, :map_of, :validations) validators = build_validators(validations) spec_opts = { type: t, validators: validators } if seq_of build_seq_of(spec_opts, seq_of) elsif map_of build_map_of(spec_opts, map_of) else new(spec_opts) end end |
Instance Method Details
#to_data(value) ⇒ Object
82 83 84 85 86 87 88 89 90 |
# File 'lib/typed_model/type_def.rb', line 82 def to_data(value) if value_type.respond_to?(:to_data) value_type.to_data(value) elsif value.respond_to?(:to_data) value.to_data else value end end |
#typecast_value(v) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/typed_model/type_def.rb', line 56 def typecast_value(v) return v unless value_type if value_type.respond_to?(:typecast_value) value_type.typecast_value(v) elsif recognized_scalar_type? Types.typecast(value_type, v) elsif value_type.is_a?(Class) instantiate_type(v) else raise "unrecognized type '#{value_type.inspect}'" end end |
#validate(value, errors, key_prefix) ⇒ Object
70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/typed_model/type_def.rb', line 70 def validate(value, errors, key_prefix) validate_recognized_types(errors, key_prefix, value) execute_validators(errors, key_prefix, value) if value_type.respond_to?(:validate) value_type.validate(value, errors, key_prefix) end merge_value_errors(value, errors, key_prefix) end |