Class: Measured::UnitSystem
- Inherits:
-
Object
- Object
- Measured::UnitSystem
- Defined in:
- lib/measured/unit_system.rb
Instance Attribute Summary collapse
-
#units ⇒ Object
readonly
Returns the value of attribute units.
Instance Method Summary collapse
- #convert(value, from:, to:) ⇒ Object
-
#initialize(units) ⇒ UnitSystem
constructor
A new instance of UnitSystem.
- #unit?(name) ⇒ Boolean
- #unit_for(name) ⇒ Object
- #unit_for!(name) ⇒ Object
- #unit_names ⇒ Object
- #unit_names_with_aliases ⇒ Object
- #unit_or_alias?(name) ⇒ Boolean
Constructor Details
#initialize(units) ⇒ UnitSystem
Returns a new instance of UnitSystem.
4 5 6 |
# File 'lib/measured/unit_system.rb', line 4 def initialize(units) @units = units.map { |unit| unit.with_unit_system(self) } end |
Instance Attribute Details
#units ⇒ Object (readonly)
Returns the value of attribute units.
2 3 4 |
# File 'lib/measured/unit_system.rb', line 2 def units @units end |
Instance Method Details
#convert(value, from:, to:) ⇒ Object
35 36 37 38 39 40 41 |
# File 'lib/measured/unit_system.rb', line 35 def convert(value, from:, to:) conversion = conversion_table.fetch(from.name, {})[to.name] raise Measured::UnitError, "Cannot find conversion entry from #{from} to #{to}" unless conversion value.to_r * conversion end |
#unit?(name) ⇒ Boolean
20 21 22 23 |
# File 'lib/measured/unit_system.rb', line 20 def unit?(name) unit = unit_for(name) unit ? unit.name == name.to_s : false end |
#unit_for(name) ⇒ Object
25 26 27 |
# File 'lib/measured/unit_system.rb', line 25 def unit_for(name) unit_name_to_unit[name.to_s] end |
#unit_for!(name) ⇒ Object
29 30 31 32 33 |
# File 'lib/measured/unit_system.rb', line 29 def unit_for!(name) unit = unit_for(name) raise Measured::UnitError, "Unit '#{name}' does not exist" unless unit unit end |
#unit_names ⇒ Object
12 13 14 |
# File 'lib/measured/unit_system.rb', line 12 def unit_names @unit_names ||= @units.map(&:name).sort end |
#unit_names_with_aliases ⇒ Object
8 9 10 |
# File 'lib/measured/unit_system.rb', line 8 def unit_names_with_aliases @unit_names_with_aliases ||= @units.flat_map(&:names).sort end |
#unit_or_alias?(name) ⇒ Boolean
16 17 18 |
# File 'lib/measured/unit_system.rb', line 16 def unit_or_alias?(name) !!unit_for(name) end |