module DaisybillApi::Ext::Attributes::TypeCastings

Public Class Methods

convert_to(value, type) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 8
def convert_to(value, type)
  return to_array(value, type.first) if type.is_a? Array
  return if value.nil? || (value.is_a?(String) && value.strip.empty?)
  return to_class(value, type) if type.is_a? Class
  case type
    when :integer
      to_integer(value)
    when :string
      to_string(value)
    when :date
      to_date(value)
    when :datetime
      to_datetime(value)
    when :boolean
      to_boolean(value)
    when :attachment
      to_attachment(value)
    when :float
      to_float(value)
    when :hash
      to_hash(value)
    else
      raise "Unknown Type"
  end
end

Private Class Methods

to_array(values, type) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 67
def to_array(values, type)
  return [] if values.nil?
  values.map { |value| convert_to(value, type) }
end
to_attachment(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 72
def to_attachment(value)
  return open(value) if value.is_a? String
  value if value.is_a?(StringIO) || value.kind_of?(IO)
end
to_boolean(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 54
def to_boolean(value)
  !!value
end
to_class(attributes, type) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 62
def to_class(attributes, type)
  return attributes if attributes.is_a? type
  type.new(attributes) rescue nil
end
to_date(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 36
def to_date(value)
  return value.to_date if value.respond_to? :to_date
  Date.parse value rescue nil
end
to_datetime(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 41
def to_datetime(value)
  return value.to_datetime if value.respond_to? :to_datetime
  DateTime.iso8601 value rescue nil
end
to_float(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 58
def to_float(value)
  value.to_f rescue nil
end
to_hash(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 77
def to_hash(value)
  value.to_h rescue nil
end
to_integer(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 46
def to_integer(value)
  value.to_i rescue nil
end
to_string(value) click to toggle source
# File lib/daisybill_api/ext/attributes/type_castings.rb, line 50
def to_string(value)
  value.to_s rescue nil
end