Class: Stannum::Contracts::MapContract
- Inherits:
-
Stannum::Contract
- Object
- Stannum::Constraints::Base
- Base
- Stannum::Contract
- Stannum::Contracts::MapContract
- Defined in:
- lib/stannum/contracts/map_contract.rb
Overview
A MapContract defines constraints on an hash-like object’s values.
Direct Known Subclasses
Defined Under Namespace
Classes: Builder
Constant Summary
Constants inherited from Stannum::Constraints::Base
Stannum::Constraints::Base::NEGATED_TYPE, Stannum::Constraints::Base::TYPE
Instance Attribute Summary
Attributes inherited from Stannum::Constraints::Base
Instance Method Summary collapse
-
#add_key_constraint(key, constraint, sanity: false, **options) ⇒ self
Adds a key constraint to the contract.
-
#allow_extra_keys? ⇒ true, false
If true, the contract will match hashes with keys that are not constrained by the contract.
-
#expected_keys ⇒ Array
The list of keys expected by the key constraints.
-
#initialize(allow_extra_keys: false, **options, &block) ⇒ MapContract
constructor
A new instance of MapContract.
- #with_options(**options) ⇒ Object
Methods inherited from Stannum::Contract
#add_constraint, #add_property_constraint
Methods inherited from Base
#==, #add_constraint, #concat, #does_not_match?, #each_constraint, #each_pair, #errors_for, #match, #matches?, #negated_errors_for, #negated_match
Methods inherited from Stannum::Constraints::Base
#==, #clone, #does_not_match?, #dup, #errors_for, #match, #matches?, #message, #negated_errors_for, #negated_match, #negated_message, #negated_type, #type
Constructor Details
#initialize(allow_extra_keys: false, **options, &block) ⇒ MapContract
105 106 107 108 109 110 111 |
# File 'lib/stannum/contracts/map_contract.rb', line 105 def initialize( allow_extra_keys: false, **, &block ) super end |
Instance Method Details
#add_key_constraint(key, constraint, sanity: false, **options) ⇒ self
Adds a key constraint to the contract.
When the contract is called, the contract will find the value of the object for the given key.
130 131 132 133 134 135 136 137 138 |
# File 'lib/stannum/contracts/map_contract.rb', line 130 def add_key_constraint(key, constraint, sanity: false, **) add_constraint( constraint, property: key, property_type: :key, sanity:, ** ) end |
#allow_extra_keys? ⇒ true, false
142 143 144 |
# File 'lib/stannum/contracts/map_contract.rb', line 142 def allow_extra_keys? [:allow_extra_keys] end |
#expected_keys ⇒ Array
147 148 149 150 151 152 153 |
# File 'lib/stannum/contracts/map_contract.rb', line 147 def expected_keys each_constraint.reduce([]) do |keys, definition| next keys unless definition.[:property_type] == :key keys << definition..fetch(:property) end end |
#with_options(**options) ⇒ Object
156 157 158 159 160 |
# File 'lib/stannum/contracts/map_contract.rb', line 156 def (**) return super unless .key?(:allow_extra_keys) raise ArgumentError, "can't change option :allow_extra_keys" end |