Class: Typecaster

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/type_casters.rb

Overview

The TypeClaster class maintains a list of typecasters and retrieves the appropriate typecaster for a given data type.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.registered_typecastersObject

Returns the list of available typecasters



9
10
11
# File 'lib/type_casters.rb', line 9

def self.registered_typecasters
  @@registered_typecasters ||= [self.instance, IntegerTypecaster.instance, FloatTypecaster.instance, BooleanTypecaster.instance]
end

.typecaster_for(typecast) ⇒ Object

Returns the first typecaster from the list of typecasters that is able to typecast the passed type.



14
15
16
17
# File 'lib/type_casters.rb', line 14

def self.typecaster_for(typecast)
  typecaster = typecast.constantize.instance rescue nil
  typecaster.present? && typecaster.is_a?(Typecaster) ? typecaster : registered_typecasters.detect{|tc| tc.type == typecast } || self.instance
end

Instance Method Details

#typeObject

Subclasses should implement this method and return the type of data it can typecast.



20
# File 'lib/type_casters.rb', line 20

def type; nil end

#typecast(value) ⇒ Object

Subclasses should implement this method and return the typecasted value of the passed value. By default, the untypecasted value will be returned.



24
25
26
# File 'lib/type_casters.rb', line 24

def typecast(value)
  value
end