Class: Parameters::Types::Hash
- Defined in:
- lib/parameters/types/hash.rb
Instance Attribute Summary collapse
-
#key_type ⇒ Object
readonly
The type to apply to all keys.
-
#value_type ⇒ Object
readonly
The type to apply to all values.
Class Method Summary collapse
-
.coerce(value) ⇒ ::Hash
Coerces a value into a Hash.
-
.key_type ⇒ Object
The key type of the Hash type.
-
.value_type ⇒ Object
The value type of the Hash type.
Instance Method Summary collapse
-
#==(other) ⇒ ::Boolean
Compares the instance type with another type.
-
#===(value) ⇒ Boolean
Determines if the Hash, and all keys/values, are related to the Type.
-
#coerce(value) ⇒ ::Hash
Coerces a value into a Hash, and coerces the keys/values of the Hash.
-
#initialize(key_type = Object, value_type = Object) ⇒ Hash
constructor
A new instance of Hash.
-
#to_ruby ⇒ Hash{Class => Class}
The Ruby Type that the Hash Type instance represents.
Methods inherited from Object
Methods inherited from Type
Constructor Details
#initialize(key_type = Object, value_type = Object) ⇒ Hash
Returns a new instance of Hash.
18 19 20 21 |
# File 'lib/parameters/types/hash.rb', line 18 def initialize(key_type=Object,value_type=Object) @key_type = key_type @value_type = value_type end |
Instance Attribute Details
#key_type ⇒ Object (readonly)
The type to apply to all keys
8 9 10 |
# File 'lib/parameters/types/hash.rb', line 8 def key_type @key_type end |
#value_type ⇒ Object (readonly)
The type to apply to all values
11 12 13 |
# File 'lib/parameters/types/hash.rb', line 11 def value_type @value_type end |
Class Method Details
.coerce(value) ⇒ ::Hash
Coerces a value into a Hash.
56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/parameters/types/hash.rb', line 56 def self.coerce(value) case value when ::Hash value when ::Array ::Hash[*value] else if value.respond_to?(:to_hash) value.to_hash else raise(TypeError,"cannot coerce #{value.inspect} into a Hash") end end end |
Instance Method Details
#==(other) ⇒ ::Boolean
Compares the instance type with another type.
93 94 95 96 97 98 |
# File 'lib/parameters/types/hash.rb', line 93 def ==(other) super(other) && ( (@key_type == other.key_type) && (@value_type == other.value_type) ) end |
#===(value) ⇒ Boolean
Determines if the Hash, and all keys/values, are related to the Type.
109 110 111 112 113 114 |
# File 'lib/parameters/types/hash.rb', line 109 def ===(value) (self.class === value) && value.entries.all? do |k,v| (@key_type.nil? || @key_type === k) && (@value_type.nil? || @value_type === v) end end |
#coerce(value) ⇒ ::Hash
Coerces a value into a Hash, and coerces the keys/values of the Hash.
125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/parameters/types/hash.rb', line 125 def coerce(value) hash = super(value) coerced_hash = {} hash.each do |k,v| k = @key_type.coerce(k) if @key_type v = @value_type.coerce(v) if @value_type coerced_hash[k] = v end return coerced_hash end |