class Measured::Measurable
Constants
- DEFAULT_FORMAT_STRING
Attributes
unit[R]
value[R]
Public Class Methods
name()
click to toggle source
# File lib/measured/measurable.rb, line 86 def name to_s.split("::").last.underscore.humanize.downcase end
new(value, unit)
click to toggle source
# File lib/measured/measurable.rb, line 9 def initialize(value, unit) raise Measured::UnitError, "Unit value cannot be blank" if value.blank? @unit = unit_from_unit_or_name!(unit) @value = case value when Float BigDecimal(value, Float::DIG) when BigDecimal, Rational value when Integer Rational(value) else BigDecimal(value) end @value_string = begin str = case value when Rational value.denominator == 1 ? value.numerator.to_s : value.to_f.to_s when BigDecimal value.to_s("F") else value.to_f.to_s end str.gsub(/\.0*\Z/, "") end.freeze end
parse(string)
click to toggle source
# File lib/measured/measurable.rb, line 90 def parse(string) new(*Measured::Parser.parse_string(string)) end
unit_system()
click to toggle source
# File lib/measured/measurable.rb, line 78 def unit_system raise "`Measurable` does not have a `unit_system` object. You cannot directly subclass `Measurable`. Instead, build a new unit system by calling `Measured.build`." end
Public Instance Methods
<=>(other)
click to toggle source
# File lib/measured/measurable.rb, line 67 def <=>(other) if other.is_a?(self.class) value <=> other.convert_to(unit).value else nil end end
convert_to(new_unit)
click to toggle source
# File lib/measured/measurable.rb, line 37 def convert_to(new_unit) new_unit = unit_from_unit_or_name!(new_unit) return self if new_unit == unit new_value = unit.unit_system.convert(value, from: unit, to: new_unit) self.class.new(new_value, new_unit) end
format(format_string=nil)
click to toggle source
# File lib/measured/measurable.rb, line 46 def format(format_string=nil) kwargs = { value: self.value, unit: self.unit, } (format_string || DEFAULT_FORMAT_STRING) % kwargs end
humanize()
click to toggle source
# File lib/measured/measurable.rb, line 58 def humanize unit_string = value == 1 ? unit.name : ActiveSupport::Inflector.pluralize(unit.name) "#{@value_string} #{unit_string}" end
inspect()
click to toggle source
# File lib/measured/measurable.rb, line 63 def inspect "#<#{self.class}: #{@value_string} #{unit.inspect}>" end
to_s()
click to toggle source
# File lib/measured/measurable.rb, line 54 def to_s "#{@value_string} #{unit.name}" end
Private Instance Methods
unit_from_unit_or_name!(value)
click to toggle source
# File lib/measured/measurable.rb, line 97 def unit_from_unit_or_name!(value) value.is_a?(Measured::Unit) ? value : self.class.unit_system.unit_for!(value) end