Class: StrongJSON::Type::Enum

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(types, detector = nil) ⇒ Enum

Returns a new instance of Enum.



305
306
307
308
# File 'lib/strong_json/type.rb', line 305

def initialize(types, detector = nil)
  @types = types
  @detector = detector
end

Instance Attribute Details

#detectorObject (readonly)

Returns the value of attribute detector.



303
304
305
# File 'lib/strong_json/type.rb', line 303

def detector
  @detector
end

#typesObject (readonly)

Returns the value of attribute types.



302
303
304
# File 'lib/strong_json/type.rb', line 302

def types
  @types
end

Instance Method Details

#==(other) ⇒ Object



332
333
334
335
336
337
338
# File 'lib/strong_json/type.rb', line 332

def ==(other)
  if other.is_a?(Enum)
    # @type var other: Enum<any>
    other.types == types &&
      other.detector == detector
  end
end

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

Raises:



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/strong_json/type.rb', line 314

def coerce(value, path: ErrorPath.root(self))
  if d = detector
    type = d[value]
    if type && types.include?(type)
      return type.coerce(value, path: path.expand(type: type))
    end
  end

  types.each do |ty|
    begin
      return ty.coerce(value, path: path.expand(type: ty))
    rescue UnexpectedAttributeError, TypeError # rubocop:disable Lint/HandleExceptions
    end
  end

  raise TypeError.new(path: path, value: value)
end

#to_sObject



310
311
312
# File 'lib/strong_json/type.rb', line 310

def to_s
  self.alias&.to_s || "enum(#{types.map(&:to_s).join(", ")})"
end