Sha256: 137b817d61479b8aacd40ba594b40dec02d53ae64ba3834d7b0982a049b2827a

Contents?: true

Size: 1.26 KB

Versions: 15

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

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

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

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

  contract(Any, Kwargs[name: String, role: Nilor[Symbol, ArrayOf[Symbol]]] => Rational)
  def db_load(value, name:, role: nil)
    cast(value, name: name, role: role)
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
ree_lib-1.0.85 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.84 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.83 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.82 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.81 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.80 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.79 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.78 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.77 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.76 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.75 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.74 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.73 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.72 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb
ree_lib-1.0.71 lib/ree_lib/packages/ree_mapper/package/ree_mapper/types/rational.rb