Sha256: 0b53a3aa222c05baa6b233fa8b8e2250434c25f7ad82bc21e6cc7948f44195fe

Contents?: true

Size: 1.39 KB

Versions: 7

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

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

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

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

  contract(Any, Kwargs[name: String, location: Nilor[String]] => Rational)
  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/rational.rb
ree_lib-1.0.92 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.91 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.90 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.89 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.88 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.87 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb