class Anyway::TypeRegistry

Contains a mapping between type IDs/names and deserializers

Attributes

registry[R]

Public Class Methods

default() click to toggle source
# File lib/anyway/type_casting.rb, line 7
def default
  @default ||= TypeRegistry.new
end
new() click to toggle source
# File lib/anyway/type_casting.rb, line 12
def initialize
  @registry = {}
end

Public Instance Methods

accept(name_or_object, &block) click to toggle source
# File lib/anyway/type_casting.rb, line 16
def accept(name_or_object, &block)
  if !block && !name_or_object.respond_to?(:call)
    raise ArgumentError, "Please, provide a type casting block or an object implementing #call(val) method"
  end

  registry[name_or_object] = block || name_or_object
end
deserialize(raw, type_id, array: false) click to toggle source
# File lib/anyway/type_casting.rb, line 24
def deserialize(raw, type_id, array: false)
  return if raw.nil?

  caster =
    if type_id.is_a?(Symbol) || type_id.nil?
      registry.fetch(type_id) { raise ArgumentError, "Unknown type: #{type_id}" }
    else
      raise ArgumentError, "Type must implement #call(val): #{type_id}" unless type_id.respond_to?(:call)
      type_id
    end

  if array
    raw_arr = raw.is_a?(String) ? raw.split(/\s*,\s*/) : Array(raw)
    raw_arr.map { caster.call(it) }
  else
    caster.call(raw)
  end
end
dup() click to toggle source
# File lib/anyway/type_casting.rb, line 43
def dup
  new_obj = self.class.allocate
  new_obj.instance_variable_set(:@registry, registry.dup)
  new_obj
end