Class: JsonApiServer::Cast

Inherits:
Object
  • Object
show all
Defined in:
lib/json_api_server/cast.rb

Overview

Converts string params to data types.

Class Method Summary collapse

Class Method Details

.to(value, type = 'String') ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/json_api_server/cast.rb', line 12

def to(value, type = 'String')
  case type.to_s
  when 'String'
    apply_cast(value, :to_string)
  when 'Integer'
    apply_cast(value, :to_integer)
  when 'Date'
    apply_cast(value, :to_date)
  when 'DateTime'
    apply_cast(value, :to_datetime)
  when 'Float'
    apply_cast(value, :to_float)
  when 'BigDecimal'
    apply_cast(value, :to_decimal)
  else
    apply_cast(value, :to_string)
  end
end

.to_date(string) ⇒ Object



61
62
63
64
65
# File 'lib/json_api_server/cast.rb', line 61

def to_date(string)
  Date.parse(string)
rescue
  nil
end

.to_datetime(string) ⇒ Object

Calls DateTime.parse on string. If datetime responds to :in_time_zone, it calls it.



70
71
72
73
74
75
# File 'lib/json_api_server/cast.rb', line 70

def to_datetime(string)
  d = DateTime.parse(string)
  d.respond_to?(:in_time_zone) ? d.in_time_zone : d
rescue
  nil
end

.to_decimal(string) ⇒ Object

Converts to BigDecimal and calls to_f on it. Returns zero if it can’t be converted.



52
53
54
55
56
57
# File 'lib/json_api_server/cast.rb', line 52

def to_decimal(string)
  d = BigDecimal.new(string)
  d.to_f
rescue
  0.0
end

.to_float(string) ⇒ Object

Calls to_f on object. Returns zero if it can’t be converted.



44
45
46
47
48
# File 'lib/json_api_server/cast.rb', line 44

def to_float(string)
  string.to_f
rescue
  0.0
end

.to_integer(string) ⇒ Object

Calls to_i on object. Returns zero if it can’t be converted.



37
38
39
40
41
# File 'lib/json_api_server/cast.rb', line 37

def to_integer(string)
  string.to_i
rescue
  0
end

.to_string(string) ⇒ Object

Calls to_s on object.



32
33
34
# File 'lib/json_api_server/cast.rb', line 32

def to_string(string)
  string.to_s
end