Sha256: e965a40af7e1647191291c579b228f6148132aa9302124b8a7d2179ceffa9e92
Contents?: true
Size: 1.42 KB
Versions: 10
Compression:
Stored size: 1.42 KB
Contents
class Measured::Unit include Comparable def initialize(name, aliases: [], value: nil) @name = name.to_s @names = ([@name] + aliases.map{|n| n.to_s }).sort @conversion_amount, @conversion_unit = parse_value(value) if value end attr_reader :name, :names, :conversion_amount, :conversion_unit def to_s if conversion_string "#{ @name } (#{ conversion_string })" else @name end end def inspect "#<Measured::Unit: #{ @name } (#{ @names.join(", ") }) #{ conversion_string }>" end def <=>(other) if self.class == other.class if other.names != @names other.names <=> @names else other.conversion_amount <=> @conversion_amount end else @name <=> other end end def inverse_conversion_amount if conversion_amount.is_a?(Rational) Rational(conversion_amount.denominator, conversion_amount.numerator) else BigDecimal(1) / conversion_amount end end private def conversion_string "#{ conversion_amount } #{ conversion_unit }" if @conversion_amount || @conversion_unit end def parse_value(tokens) tokens = tokens.split(" ") if tokens.is_a?(String) raise Measured::UnitError, "Cannot parse 'number unit' or [number, unit] formatted tokens from #{ tokens }." unless tokens.size == 2 tokens[0] = BigDecimal(tokens[0]) unless tokens[0].is_a?(BigDecimal) || tokens[0].is_a?(Rational) tokens end end
Version data entries
10 entries across 10 versions & 1 rubygems