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

Inherits:
TypeClass
  • Object
show all
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 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.



220
221
222
223
# File 'lib/yarrow/schema/types.rb', line 220

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.



217
218
219
# File 'lib/yarrow/schema/types.rb', line 217

def key_type
  @key_type
end

Class Method Details

.of(map_spec) ⇒ Object

include CompoundType



202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/yarrow/schema/types.rb', line 202

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

#accept_elements(accept_type, constructor = :new, options = nil) ⇒ Object



225
226
227
228
# File 'lib/yarrow/schema/types.rb', line 225

def accept_elements(accept_type, constructor=:new, options=nil)
  value_type.accept(accept_type, constructor, options)
  self
end

#check(input) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
# File 'lib/yarrow/schema/types.rb', line 230

def check(input)
  result = {}

  input.each_pair do |key, value|
    checked_key = key_type.cast(key)
    checked_value = value_type.cast(value, { key: checked_key })
    result[checked_key] = checked_value
  end

  result
end