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

#initializeConverterFactory

Returns a new instance of ConverterFactory.



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

def initialize
  @converters = Array.new
end

Instance Attribute Details

#convertersObject (readonly)

Returns the value of attribute converters.



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

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:



25
26
27
28
# File 'lib/synapse/serialization/converter_factory.rb', line 25

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



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

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

  @converters.each do |converter|
    if converter.source_type == source_type && converter.target_type == target_type
      return converter
    end
  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)


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

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)


16
17
18
# File 'lib/synapse/serialization/converter_factory.rb', line 16

def register(converter)
  @converters.push converter
end