Class: Measured::UnitSystem

Inherits:
Object
  • Object
show all
Defined in:
lib/measured/unit_system.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(units, cache: nil) ⇒ UnitSystem

Returns a new instance of UnitSystem.



5
6
7
8
9
10
11
12
13
14
# File 'lib/measured/unit_system.rb', line 5

def initialize(units, cache: nil)
  @units = units.map { |unit| unit.with_unit_system(self) }
  @unit_names = @units.map(&:name).sort.freeze
  @unit_names_with_aliases = @units.flat_map(&:names).sort.freeze
  @unit_name_to_unit = @units.each_with_object({}) do |unit, hash|
    unit.names.each { |name| hash[name.to_s] = unit }
  end
  @conversion_table_builder = Measured::ConversionTableBuilder.new(@units, cache: cache)
  @conversion_table = @conversion_table_builder.to_h.freeze
end

Instance Attribute Details

#unit_namesObject (readonly)

Returns the value of attribute unit_names.



3
4
5
# File 'lib/measured/unit_system.rb', line 3

def unit_names
  @unit_names
end

#unit_names_with_aliasesObject (readonly)

Returns the value of attribute unit_names_with_aliases.



3
4
5
# File 'lib/measured/unit_system.rb', line 3

def unit_names_with_aliases
  @unit_names_with_aliases
end

#unitsObject (readonly)

Returns the value of attribute units.



3
4
5
# File 'lib/measured/unit_system.rb', line 3

def units
  @units
end

Instance Method Details

#cached?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/measured/unit_system.rb', line 47

def cached?
  @conversion_table_builder.cached?
end

#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

Returns:

  • (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_or_alias?(name) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/measured/unit_system.rb', line 16

def unit_or_alias?(name)
  !!unit_for(name)
end

#update_cacheObject



43
44
45
# File 'lib/measured/unit_system.rb', line 43

def update_cache
  @conversion_table_builder.update_cache
end