class JsonApiServer::Cast
Converts string params to data types.
Public Class Methods
to(value, type = 'String')
click to toggle source
# 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)
click to toggle source
Calls Date.parse on string. ruby-doc.org/stdlib-2.4.0/libdoc/date/rdoc/Date.html#method-c-parse
# File lib/json_api_server/cast.rb, line 61 def to_date(string) Date.parse(string) rescue nil end
to_datetime(string)
click to toggle source
Calls DateTime.parse on string. If datetime responds to :in_time_zone, it calls it.
# 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)
click to toggle source
Converts to BigDecimal and calls to_f on it. Returns zero if it can't be converted.
# 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)
click to toggle source
Calls to_f on object. Returns zero if it can't be converted.
# File lib/json_api_server/cast.rb, line 44 def to_float(string) string.to_f rescue 0.0 end
to_integer(string)
click to toggle source
Calls to_i on object. Returns zero if it can't be converted.
# File lib/json_api_server/cast.rb, line 37 def to_integer(string) string.to_i rescue 0 end
to_string(string)
click to toggle source
Calls to_s on object.
# File lib/json_api_server/cast.rb, line 32 def to_string(string) string.to_s end
Protected Class Methods
apply_cast(val, cast_method)
click to toggle source
If val is an array, it casts each value. Otherwise, it casts the value.
# File lib/json_api_server/cast.rb, line 80 def apply_cast(val, cast_method) if val.respond_to?(:map) val.map { |v| send(cast_method, v) } else send(cast_method, val) end end