Class: EPlat::TypeCoercer

Inherits:
Object
  • Object
show all
Defined in:
lib/e_plat/type_coercer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type_schema) ⇒ TypeCoercer

Returns a new instance of TypeCoercer.



11
12
13
# File 'lib/e_plat/type_coercer.rb', line 11

def initialize(type_schema)
	@type_schema = type_schema
end

Instance Attribute Details

#type_schemaObject

Returns the value of attribute type_schema.



5
6
7
# File 'lib/e_plat/type_coercer.rb', line 5

def type_schema
  @type_schema
end

Instance Method Details

#inspectObject



7
8
9
# File 'lib/e_plat/type_coercer.rb', line 7

def inspect
  "#<#{self.class}>"
end

#safe_coerce(value, type) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/e_plat/type_coercer.rb', line 27

def safe_coerce(value, type)
	case type
	when "boolean"
		ActiveModel::Type::Boolean.new.cast(value)
	when "integer"
		"EPlat::Types::Coercible::#{ type.capitalize }".constantize[value]
	else
		value.send to_type_method(type)
	end
rescue 
	value
end

#type_value!(key, value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/e_plat/type_coercer.rb', line 15

def type_value!(key, value) 
	type = type_schema[key].try(:downcase)
	
	if type.nil?
		return value
	elsif value.nil? or value == "null"
		return unless type == "array" or type == "hash"
	end

	safe_coerce(value, type)
end