class ActiveType::TypeCaster

Public Class Methods

get(type) click to toggle source
# File lib/active_type/type_caster.rb, line 4
def self.get(type)
  native_caster = if ActiveRecord::VERSION::STRING < '4.2'
    NativeCasters::DelegateToColumn.new(type)
  elsif ActiveRecord::VERSION::STRING < '5'
    NativeCasters::DelegateToRails4Type.new(type)
  else
    NativeCasters::DelegateToRails5Type.new(type)
  end
  new(type, native_caster)
end
new(type, native_caster) click to toggle source
# File lib/active_type/type_caster.rb, line 15
def initialize(type, native_caster)
  @type = type
  @native_caster = native_caster
end

Public Instance Methods

native_type_cast_from_user(value) click to toggle source
# File lib/active_type/type_caster.rb, line 33
def native_type_cast_from_user(value)
  @native_caster.type_cast_from_user(value)
end
type_cast_from_user(value) click to toggle source
# File lib/active_type/type_caster.rb, line 20
def type_cast_from_user(value)
  # For some reason, Rails defines additional type casting logic
  # outside the classes that have that responsibility.
  case @type
  when :integer
    cast_integer(value)
  when :timestamp, :datetime
    cast_time(value)
  else
    native_type_cast_from_user(value)
  end
end

Private Instance Methods

cast_integer(value) click to toggle source
# File lib/active_type/type_caster.rb, line 39
def cast_integer(value)
  if value == ''
    nil
  else
    native_type_cast_from_user(value)
  end
end
cast_time(value) click to toggle source
# File lib/active_type/type_caster.rb, line 47
def cast_time(value)
  time = nil
  if ActiveRecord::Base.time_zone_aware_attributes
    if value.is_a?(String)
      time = Time.zone.parse(value) rescue nil
    end
    time ||= native_type_cast_from_user(value)
    if time
      if value.is_a?(String) && value !~ /[+\-Z][\d:]*$/
        # time was given without an explicit zone, so assume it was given in Time.zone
        ActiveSupport::TimeWithZone.new(nil, Time.zone, time)
      else
        time.in_time_zone rescue time
      end
    end
  else
    native_type_cast_from_user(value)
  end
end