Module: Hashme::PropertyCasting

Extended by:
PropertyCasting
Included in:
PropertyCasting
Defined in:
lib/hashme/property_casting.rb

Overview

Special property casting for reveiving data from sources without Ruby types, such as query parameters from an API or JSON documents.

Most of this code is stolen from CouchRest Model typecasting, with a few simplifications.

Constant Summary collapse

CASTABLE_TYPES =
[String, Symbol, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class]

Instance Method Summary collapse

Instance Method Details

#cast(property, owner, value) ⇒ Object

Automatically typecast the provided value into an instance of the provided type.



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hashme/property_casting.rb', line 13

def cast(property, owner, value)
  return nil if value.nil?
  type = property.type
  if value.instance_of?(type) || type == Object
    value
  elsif CASTABLE_TYPES.include?(type)
    send('typecast_to_'+type.to_s.downcase, value)
  else
    type.new(value)
  end
end