Class: Measured::Measurable

Inherits:
Numeric
  • Object
show all
Extended by:
Forwardable
Includes:
Arithmetic
Defined in:
lib/measured/measurable.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Arithmetic

#+, #-, #-@, #coerce, #scale, #to_i

Constructor Details

#initialize(value, unit) ⇒ Measurable

Returns a new instance of Measurable.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/measured/measurable.rb', line 6

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 + 1)
  when BigDecimal, Rational
    value
  when Integer
    Rational(value)
  else
    BigDecimal(value)
  end
end

Instance Attribute Details

#unitObject (readonly)

Returns the value of attribute unit.



4
5
6
# File 'lib/measured/measurable.rb', line 4

def unit
  @unit
end

#valueObject (readonly)

Returns the value of attribute value.



4
5
6
# File 'lib/measured/measurable.rb', line 4

def value
  @value
end

Class Method Details

.nameObject



65
66
67
# File 'lib/measured/measurable.rb', line 65

def name
  to_s.split("::").last.underscore.humanize.downcase
end

.parse(string) ⇒ Object



69
70
71
# File 'lib/measured/measurable.rb', line 69

def parse(string)
  new(*Measured::Parser.parse_string(string))
end

.unit_systemObject



57
58
59
# File 'lib/measured/measurable.rb', line 57

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

Instance Method Details

#<=>(other) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/measured/measurable.rb', line 46

def <=>(other)
  if other.is_a?(self.class)
    value <=> other.convert_to(unit).value
  else
    nil
  end
end

#convert_to(new_unit) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/measured/measurable.rb', line 22

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

#humanizeObject



35
36
37
38
39
40
# File 'lib/measured/measurable.rb', line 35

def humanize
  @humanize ||= begin
    unit_string = value == 1 ? unit.name : ActiveSupport::Inflector.pluralize(unit.name)
    "#{value_string} #{unit_string}"
  end
end

#inspectObject



42
43
44
# File 'lib/measured/measurable.rb', line 42

def inspect
  @inspect ||= "#<#{self.class}: #{value_string} #{unit.inspect}>"
end

#to_sObject



31
32
33
# File 'lib/measured/measurable.rb', line 31

def to_s
  @to_s ||= "#{value_string} #{unit.name}"
end