Class: ValueSemantics::Attribute
- Inherits:
-
Object
- Object
- ValueSemantics::Attribute
- Defined in:
- lib/value_semantics.rb
Instance Attribute Summary collapse
-
#coercer ⇒ Object
readonly
Returns the value of attribute coercer.
-
#default_value ⇒ Object
readonly
Returns the value of attribute default_value.
-
#has_default ⇒ Object
readonly
Returns the value of attribute has_default.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
Instance Method Summary collapse
- #determine_from!(attr_hash, value_object) ⇒ Object
-
#initialize(name:, has_default:, default_value:, validator:, coercer:) ⇒ Attribute
constructor
A new instance of Attribute.
- #instance_variable ⇒ Object
- #validate?(value) ⇒ Boolean
Constructor Details
#initialize(name:, has_default:, default_value:, validator:, coercer:) ⇒ Attribute
Returns a new instance of Attribute.
80 81 82 83 84 85 86 87 |
# File 'lib/value_semantics.rb', line 80 def initialize(name:, has_default:, default_value:, validator:, coercer:) @name = name.to_sym @has_default = has_default @default_value = default_value @validator = validator @coercer = coercer freeze end |
Instance Attribute Details
#coercer ⇒ Object (readonly)
Returns the value of attribute coercer.
78 79 80 |
# File 'lib/value_semantics.rb', line 78 def coercer @coercer end |
#default_value ⇒ Object (readonly)
Returns the value of attribute default_value.
78 79 80 |
# File 'lib/value_semantics.rb', line 78 def default_value @default_value end |
#has_default ⇒ Object (readonly)
Returns the value of attribute has_default.
78 79 80 |
# File 'lib/value_semantics.rb', line 78 def has_default @has_default end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
78 79 80 |
# File 'lib/value_semantics.rb', line 78 def name @name end |
Instance Method Details
#determine_from!(attr_hash, value_object) ⇒ Object
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/value_semantics.rb', line 89 def determine_from!(attr_hash, value_object) raw_value = attr_hash.fetch(name) do if has_default default_value else raise ArgumentError, "Value missing for attribute '#{name}'" end end coerced_value = value_object.instance_exec(raw_value, &coercer) if validate?(coerced_value) [name, coerced_value] else raise ArgumentError, "Value for attribute '#{name}' is not valid: #{coerced_value.inspect}" end end |
#instance_variable ⇒ Object
119 120 121 |
# File 'lib/value_semantics.rb', line 119 def instance_variable '@' + name.to_s.chomp('!').chomp('?') end |
#validate?(value) ⇒ Boolean
115 116 117 |
# File 'lib/value_semantics.rb', line 115 def validate?(value) !!(@validator === value) end |