lib/reality/measure.rb in reality-0.0.2 vs lib/reality/measure.rb in reality-0.0.3
- old
+ new
@@ -1,10 +1,14 @@
module Reality
class Measure
%w[unit].each{|mod| require_relative "measure/#{mod}"}
attr_reader :amount, :unit
+
+ def Measure.coerce(amount, unit)
+ amount && unit && new(amount, unit)
+ end
def initialize(amount, unit)
@amount, @unit = Rational(amount), Unit.parse(unit)
end
@@ -12,10 +16,14 @@
check_compatibility!(other)
amount <=> other.amount
end
+ def ==(other)
+ amount == other.amount && unit == other.unit
+ end
+
def -@
self.class.new(-amount, unit)
end
def +(other)
@@ -58,27 +66,25 @@
end
include Comparable
def to_s
- '%s%s' % [formatted_amount, unit]
+ '%s%s' % [Util::Format.number(amount), unit]
end
- def inspect
- "#<%s(%s %s)>" % [self.class, formatted_amount, unit]
+ def to_f
+ amount.to_f
end
- private
+ def to_i
+ amount.to_i
+ end
- def formatted_amount
- # FIXME: really naive
- if amount.abs < 1
- amount.to_f.to_s
- else
- # see http://stackoverflow.com/a/6460145/3683228
- amount.to_i.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
- end
+ def inspect
+ "#<%s(%s %s)>" % [self.class, Util::Format.number(amount), unit]
end
+
+ private
def check_compatibility!(other)
unless other.kind_of?(self.class) && other.unit == unit
fail ArgumentError, "#{self} incompatible with #{other}"
end