Module: HappyMapper::SupportedTypes

Extended by:
SupportedTypes
Included in:
SupportedTypes
Defined in:
lib/happymapper/supported_types.rb

Defined Under Namespace

Classes: CastWhenType, NilOrAlreadyConverted

Instance Method Summary collapse

Instance 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


33
34
35
# File 'lib/happymapper/supported_types.rb', line 33

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


48
49
50
# File 'lib/happymapper/supported_types.rb', line 48

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.



10
11
12
# File 'lib/happymapper/supported_types.rb', line 10

def types
  @types ||= []
end