Sha256: d38ce089eb4091440a487832acb5901237b0f2d9196c4486407ff2a866315f56
Contents?: true
Size: 1.47 KB
Versions: 1
Compression:
Stored size: 1.47 KB
Contents
class Measured::Unit include Comparable attr_reader :name, :names, :conversion_amount, :conversion_unit, :unit_system def initialize(name, aliases: [], value: nil, unit_system: nil) @name = name.to_s @names = ([@name] + aliases.map(&:to_s)).sort @conversion_amount, @conversion_unit = parse_value(value) if value @unit_system = unit_system end def with_unit_system(unit_system) self.class.new( name, aliases: names - [name], value: conversion_string, unit_system: unit_system ) end 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 names_comparison = @names <=> other.names if names_comparison != 0 names_comparison else @conversion_amount <=> other.conversion_amount end else @name <=> other end end def inverse_conversion_amount 1 / conversion_amount.to_r 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].to_r, tokens[1]] end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
measured-2.0.0.pre2 | lib/measured/unit.rb |