Class: Measurement::Unit
- Inherits:
-
Object
- Object
- Measurement::Unit
- Includes:
- Comparable
- Defined in:
- lib/measurement/unit.rb
Instance Attribute Summary collapse
-
#groups ⇒ Object
readonly
Returns the value of attribute groups.
-
#names ⇒ Object
readonly
Returns the value of attribute names.
-
#scale ⇒ Object
readonly
Returns the value of attribute scale.
Instance Method Summary collapse
- #<=>(anOther) ⇒ Object
- #format(amount, precision = 2) ⇒ Object
- #from(amount) ⇒ Object
- #has_name?(name) ⇒ Boolean
- #in_group?(group) ⇒ Boolean
-
#initialize(scale, *args) ⇒ Unit
constructor
A new instance of Unit.
- #prefix ⇒ Object
- #suffix ⇒ Object
- #to(amount) ⇒ Object
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
#groups ⇒ Object (readonly)
Returns the value of attribute groups.
5 6 7 |
# File 'lib/measurement/unit.rb', line 5 def groups @groups end |
#names ⇒ Object (readonly)
Returns the value of attribute names.
5 6 7 |
# File 'lib/measurement/unit.rb', line 5 def names @names end |
#scale ⇒ Object (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
18 19 20 |
# File 'lib/measurement/unit.rb', line 18 def has_name?(name) names.include?(name) end |
#in_group?(group) ⇒ Boolean
22 23 24 |
# File 'lib/measurement/unit.rb', line 22 def in_group?(group) groups.include?(group.to_sym) end |
#prefix ⇒ Object
39 40 41 |
# File 'lib/measurement/unit.rb', line 39 def prefix @options[:prefix] || '' end |
#suffix ⇒ Object
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 |