Class: Measurement::Unit

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/measurement/unit.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scale, *args) ⇒ Unit

Returns a new instance of Unit.



7
8
9
10
11
12
# File 'lib/measurement/unit.rb', line 7

def initialize(scale, *args)
  @options = args.last.is_a?(Hash) ? args.pop : {}
  @names = args
  @scale = scale
  @groups = [@options[:group]].flatten
end

Instance Attribute Details

#groupsObject (readonly)

Returns the value of attribute groups.



5
6
7
# File 'lib/measurement/unit.rb', line 5

def groups
  @groups
end

#namesObject (readonly)

Returns the value of attribute names.



5
6
7
# File 'lib/measurement/unit.rb', line 5

def names
  @names
end

#scaleObject (readonly)

Returns the value of attribute scale.



5
6
7
# File 'lib/measurement/unit.rb', line 5

def scale
  @scale
end

Instance Method Details

#<=>(anOther) ⇒ Object



14
15
16
# File 'lib/measurement/unit.rb', line 14

def <=>(anOther)
  scale <=> anOther.scale
end

#format(amount, precision = 2) ⇒ Object



34
35
36
37
# File 'lib/measurement/unit.rb', line 34

def format(amount, precision = 2)
  number = ("%.#{precision}f" % to(amount)).sub(/(\.\d*)0/, '\1')
  prefix + number + suffix
end

#from(amount) ⇒ Object



26
27
28
# File 'lib/measurement/unit.rb', line 26

def from(amount)
  amount.to_f * @scale
end

#has_name?(name) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/measurement/unit.rb', line 18

def has_name?(name)
  names.include?(name)
end

#in_group?(group) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/measurement/unit.rb', line 22

def in_group?(group)
  groups.include?(group.to_sym)
end

#prefixObject



39
40
41
# File 'lib/measurement/unit.rb', line 39

def prefix
  @options[:prefix] || ''
end

#suffixObject



43
44
45
# File 'lib/measurement/unit.rb', line 43

def suffix
  @options[:suffix] || ''
end

#to(amount) ⇒ Object



30
31
32
# File 'lib/measurement/unit.rb', line 30

def to(amount)
  amount.to_f / @scale
end