Class: YardTypes::HashType
Overview
Enforce kind, eg HashWithIndifferentAccess{#to_sym => Array}, in case you really care that it’s indifferent. Maybe?
A HashType is specified with the syntax {KeyType => ValueType}, and indicates that all keys in the hash must be of type KeyType, and all values must be of type ValueType.
An alternate syntax for HashType is also available as Hash<A, B>, but its usage is not recommended; it is less capable than the {A => B} syntax, as some inner type constraints can not be parsed reliably.
A HashType actually only requires that the object respond to both keys and values; it should be capable of type checking any object which conforms to that interface.
Instance Attribute Summary collapse
-
#key_types ⇒ Array<Type>
readonly
The set of acceptable types for keys.
-
#value_types ⇒ Array<Type>
readonly
The set of acceptable types for values.
Attributes inherited from Type
Instance Method Summary collapse
-
#check(obj) ⇒ Boolean
trueif the object responds to bothkeysandvalues, and every key type checks against a type inkey_types, and every value type checks against a type invalue_types. -
#initialize(name, key_types, value_types) ⇒ HashType
constructor
A new instance of HashType.
-
#to_s ⇒ String
Unlike the other types, HashType can result from two alternate syntaxes; however, this method will only return the {A => B} syntax.
Methods inherited from Type
Constructor Details
#initialize(name, key_types, value_types) ⇒ HashType
Returns a new instance of HashType.
265 266 267 268 269 |
# File 'lib/yard_types/types.rb', line 265 def initialize(name, key_types, value_types) @name = name @key_types = key_types @value_types = value_types end |
Instance Attribute Details
#key_types ⇒ Array<Type> (readonly)
Returns the set of acceptable types for keys.
257 258 259 |
# File 'lib/yard_types/types.rb', line 257 def key_types @key_types end |
#value_types ⇒ Array<Type> (readonly)
Returns the set of acceptable types for values.
260 261 262 |
# File 'lib/yard_types/types.rb', line 260 def value_types @value_types end |
Instance Method Details
#check(obj) ⇒ Boolean
Returns true if the object responds to both keys and values, and every key type checks against a type in key_types, and every value type checks against a type in value_types.
286 287 288 289 290 |
# File 'lib/yard_types/types.rb', line 286 def check(obj) return false unless obj.respond_to?(:keys) && obj.respond_to?(:values) obj.keys.all? { |key| key_types.any? { |t| t.check(key) } } && obj.values.all? { |value| value_types.any? { |t| t.check(value) } } end |
#to_s ⇒ String
Unlike the other types, YardTypes::HashType can result from two alternate syntaxes; however, this method will only return the {A => B} syntax.
275 276 277 278 279 280 |
# File 'lib/yard_types/types.rb', line 275 def to_s "{%s => %s}" % [ key_types.map(&:to_s).join(', '), value_types.map(&:to_s).join(', ') ] end |