Class: Yarrow::Schema::Types::Map

Inherits:
TypeClass
  • Object
show all
Includes:
CompoundType
Defined in:
lib/yarrow/schema/types.rb

Instance Attribute Summary collapse

Attributes inherited from TypeClass

#accepts, #unit

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CompoundType

#instance, #interface, #kind

Methods inherited from TypeClass

#accept, #cast, #check_instance_of!, #check_kind_of!, #check_respond_to_all!, #check_respond_to_any!, #coerce, #should_coerce?

Constructor Details

#initialize(key_type, value_type) ⇒ Map

Returns a new instance of Map.



177
178
179
180
# File 'lib/yarrow/schema/types.rb', line 177

def initialize(key_type, value_type)
  @key_type = key_type
  super(value_type)
end

Instance Attribute Details

#key_typeObject (readonly)

Returns the value of attribute key_type.



174
175
176
# File 'lib/yarrow/schema/types.rb', line 174

def key_type
  @key_type
end

Class Method Details

.of(map_spec) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/yarrow/schema/types.rb', line 159

def self.of(map_spec)
  if map_spec.is_a?(Hash)
    if map_spec.size == 1
      key_type, value_type = map_spec.first
    else
      raise "map requires a single key => value type"
    end
  else
    key_type = Symbol
    value_type = map_spec
  end

  new(Instance.of(key_type), Instance.of(value_type))
end

Instance Method Details

#check(input) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/yarrow/schema/types.rb', line 182

def check(input)
  keys = input.keys.map do |key|
    key_type.cast(key)
  end
  values = input.values.map do |value|
    value_type.cast(value)
  end

  [keys, values].transpose.to_h
end