Class: StrongJSON::Type::Hash

Inherits:
Object
  • Object
show all
Includes:
Match, WithAlias
Defined in:
lib/strong_json/type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from WithAlias

#alias, #with_alias

Methods included from Match

#===, #=~

Constructor Details

#initialize(type) ⇒ Hash

Returns a new instance of Hash.



346
347
348
# File 'lib/strong_json/type.rb', line 346

def initialize(type)
  @type = type
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



344
345
346
# File 'lib/strong_json/type.rb', line 344

def type
  @type
end

Instance Method Details

#==(other) ⇒ Object



362
363
364
365
366
# File 'lib/strong_json/type.rb', line 362

def ==(other)
  if other.is_a?(Hash)
    other.type == type
  end
end

#coerce(value, path: ErrorPath.root(self)) ⇒ Object



350
351
352
353
354
355
356
357
358
359
360
# File 'lib/strong_json/type.rb', line 350

def coerce(value, path: ErrorPath.root(self))
  if value.is_a?(::Hash)
    (_ = {}).tap do |result|
      value.each do |k, v|
        result[k] = type.coerce(v, path: path.dig(key: k, type: type))
      end
    end
  else
    raise TypeError.new(path: path, value: value)
  end
end