Class: Synapse::Serialization::ConverterFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/synapse/serialization/converter_factory.rb

Overview

Represents a mechanism for storing and retrieving converters capable of converting content of one type to another type, for the purpose of serialization and upcasting.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeundefined



10
11
12
# File 'lib/synapse/serialization/converter_factory.rb', line 10

def initialize
  @converters = Set.new
end

Instance Attribute Details

#convertersSet<Converter> (readonly)

Returns:



7
8
9
# File 'lib/synapse/serialization/converter_factory.rb', line 7

def converters
  @converters
end

Instance Method Details

#convert(serialized_object, target_type) ⇒ SerializedObject

Convenience method for converting a given serialized object to the given target type

Parameters:

Returns:



27
28
29
30
# File 'lib/synapse/serialization/converter_factory.rb', line 27

def convert(serialized_object, target_type)
  converter = converter serialized_object.content_type, target_type
  converter.convert serialized_object
end

#converter(source_type, target_type) ⇒ Converter

Returns a converter that is capable of converting content of the given source type to the given target type, if one exists.

Parameters:

  • source_type (Class)
  • target_type (Class)

Returns:

Raises:

  • (ConversionError)

    If no converter is capable of performing the conversion



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/synapse/serialization/converter_factory.rb', line 39

def converter(source_type, target_type)
  if source_type == target_type
    return IdentityConverter.new source_type
  end

  @converters.each do |converter|
    return converter if converter.source_type == source_type &&
      converter.target_type == target_type
  end

  raise ConversionError, 'No converter capable of [%s] -> [%s]' % [source_type, target_type]
end

#has_converter?(source_type, target_type) ⇒ Boolean

Returns true if this factory contains a converter capable of converting content from the given source type to the given target type.

Parameters:

  • source_type (Class)
  • target_type (Class)

Returns:

  • (Boolean)


58
59
60
61
62
63
64
65
66
# File 'lib/synapse/serialization/converter_factory.rb', line 58

def has_converter?(source_type, target_type)
  if source_type == target_type
    return true
  end

  @converters.any? do |converter|
    converter.source_type == source_type && converter.target_type == target_type
  end
end

#register(converter) ⇒ undefined

Adds the given converter to this converter factory

Parameters:

Returns:

  • (undefined)


18
19
20
# File 'lib/synapse/serialization/converter_factory.rb', line 18

def register(converter)
  @converters.add converter
end