module Anyway::AutoCast

Constants

ARRAY_RXP

Regexp to detect array values Array value is a values that contains at least one comma and doesn’t start/end with quote or curly braces

Public Class Methods

call(val) click to toggle source
# File lib/anyway/auto_cast.rb, line 11
def call(val)
  return val unless val.is_a?(::Hash) || val.is_a?(::String)

  case val
  when Hash
    val.transform_values { call(it) }
  when ARRAY_RXP
    val.split(/\s*,\s*/).map { call(it) }
  when /\A(true|t|yes|y)\z/i
    true
  when /\A(false|f|no|n)\z/i
    false
  when /\A(nil|null)\z/i
    nil
  when /\A\d+\z/
    val.to_i
  when /\A\d*\.\d+\z/
    val.to_f
  when /\A['"].*['"]\z/
    val.gsub(/(\A['"]|['"]\z)/, "")
  else
    val
  end
end
cast_hash(obj) click to toggle source
# File lib/anyway/auto_cast.rb, line 36
def cast_hash(obj)
  obj.transform_values do |val|
    val.is_a?(::Hash) ? cast_hash(val) : call(val)
  end
end
coerce(_key, val) click to toggle source
# File lib/anyway/auto_cast.rb, line 42
def coerce(_key, val)
  call(val)
end