Sha256: dde0aaf6c10014fe014d87c907d088bfff2c2c5ddc2ddb2b22e39d2217b53f23

Contents?: true

Size: 1.42 KB

Versions: 7

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

require 'time'

class ReeMapper::Time < ReeMapper::AbstractType
  contract(Any, Kwargs[name: String, location: Nilor[String]] => Time).throws(ReeMapper::TypeError)
  def serialize(value, name:, location: nil)
    if value.class == Time
      value
    else
      raise ReeMapper::TypeError.new("`#{name}` should be a time, got `#{truncate(value.inspect)}`", location)
    end
  end

  contract(Any, Kwargs[name: String, location: Nilor[String]] => Time).throws(ReeMapper::CoercionError, ReeMapper::TypeError)
  def cast(value, name:, location: nil)
    if value.class == Time
      value
    elsif value.class == DateTime
      value.to_time
    elsif value.is_a?(String)
      begin
        Time.parse(value)
      rescue ArgumentError
        raise ReeMapper::CoercionError.new("`#{name}` is invalid time, got `#{truncate(value.inspect)}`", location)
      end
    else
      raise ReeMapper::TypeError.new("`#{name}` should be a time, got `#{truncate(value.inspect)}`", location)
    end
  end

  contract(Any, Kwargs[name: String, location: Nilor[String]] => Time).throws(ReeMapper::TypeError)
  def db_dump(value, name:, location: nil)
    serialize(value, name: name, location: location)
  end

  contract(Any, Kwargs[name: String, location: Nilor[String]] => Time).throws(ReeMapper::CoercionError, ReeMapper::TypeError)
  def db_load(value, name:, location: nil)
    cast(value, name: name, location: location)
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
ree_lib-1.0.93 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb
ree_lib-1.0.92 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb
ree_lib-1.0.91 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb
ree_lib-1.0.90 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb
ree_lib-1.0.89 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb
ree_lib-1.0.88 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb
ree_lib-1.0.87 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/time.rb