Class: Necromancer::Conversions

Inherits:
Object
  • Object
show all
Defined in:
lib/necromancer/conversions.rb

Overview

Represents the context used to configure various converters and facilitate type conversion

Constant Summary collapse

DELIMITER =
"->"

Instance Method Summary collapse

Constructor Details

#initialize(configuration = Configuration.new, map = {}) ⇒ Conversions

Creates a new conversions map

Examples:

conversion = Necromancer::Conversions.new


26
27
28
29
# File 'lib/necromancer/conversions.rb', line 26

def initialize(configuration = Configuration.new, map = {})
  @configuration = configuration
  @converter_map = map.dup
end

Instance Method Details

#[](source, target) ⇒ Converter Also known as: fetch

Retrieve converter for source and target

Parameters:

  • source (Object)

    the source of conversion

  • target (Object)

    the target of conversion

Returns:

  • (Converter)

    the converter for the source and target



55
56
57
58
59
60
# File 'lib/necromancer/conversions.rb', line 55

def [](source, target)
  key = "#{source}#{DELIMITER}#{target}"
  converter_map[key] ||
    converter_map["object#{DELIMITER}#{target}"] ||
    raise_no_type_conversion_available(key)
end

#loadObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Load converters



34
35
36
37
38
39
40
41
# File 'lib/necromancer/conversions.rb', line 34

def load
  ArrayConverters.load(self)
  BooleanConverters.load(self)
  DateTimeConverters.load(self)
  HashConverters.load(self)
  NumericConverters.load(self)
  RangeConverters.load(self)
end

#register(converter = nil, &block) ⇒ Object

Register a converter

Examples:

with simple object

conversions.register NullConverter.new(:array, :array)

with block

conversions.register do |c|
  c.source = :array
  c.target = :array
  c.convert = -> { |val, options| val }
end


76
77
78
79
80
81
82
83
84
# File 'lib/necromancer/conversions.rb', line 76

def register(converter = nil, &block)
  converter ||= Converter.create(&block)
  key = generate_key(converter)
  converter = add_config(converter, @configuration)
  return false if converter_map.key?(key)

  converter_map[key] = converter
  true
end

#to_hashHash[String, String]

Export all the conversions as hash

Returns:

  • (Hash[String, String])


91
92
93
# File 'lib/necromancer/conversions.rb', line 91

def to_hash
  converter_map.dup
end