Module: HappyMapper::SupportedTypes

Defined in:
lib/happymapper/supported_types.rb

Defined Under Namespace

Classes: CastWhenType, NilOrAlreadyConverted

Class Method Summary collapse

Class Method Details

.register(type_converter) ⇒ Object

Add a new converter to the list of supported types. A converter is an object that adheres to the protocol which is defined with two methods #apply?(value,convert_to_type) and #apply(value).

Examples:

Defining a class that would process `nil` or values that have

already been converted.

  class NilOrAlreadyConverted
    def apply?(value,convert_to_type)
      value.kind_of?(convert_to_type) || value.nil?
    end

    def apply(value)
      value
    end
  end

35
36
37
# File 'lib/happymapper/supported_types.rb', line 35

def register(type_converter)
  types.push type_converter
end

.register_type(type, &block) ⇒ Object

An additional shortcut registration method that assumes that you want to perform a conversion on a specific type. A block is provided which is the operation to perform when #apply(value) has been called.

Examples:

Registering a DateTime parser


HappyMapper::SupportedTypes.register_type DateTime do |value|
  DateTime.parse(value,to_s)
end

50
51
52
# File 'lib/happymapper/supported_types.rb', line 50

def register_type(type, &block)
  register CastWhenType.new(type, &block)
end

.typesObject

All of the registerd supported types that can be parsed.

All types defined here are set through #register.


12
13
14
# File 'lib/happymapper/supported_types.rb', line 12

def types
  @types ||= []
end