Sha256: f54975476a28ab6b347195bcc8bc235c9a302472283dc92a8494db18f103a276

Contents?: true

Size: 1018 Bytes

Versions: 20

Compression:

Stored size: 1018 Bytes

Contents

# -*- encoding: utf-8 -*-
# -*- frozen_string_literal: true -*-
# -*- warn_indent: true -*-

module UnitMeasurements
  class UnitGroup
    attr_reader :units

    def initialize(units)
      @units = units.map { |unit| unit.with(unit_group: self) }
    end

    def unit_for(name)
      unit_name_to_unit(name)
    end

    def unit_for!(name)
      unit = unit_for(name)
      raise UnitError, name unless unit
      unit
    end
    alias_method :[], :unit_for!

    def unit_with_name_and_aliases
      units.each_with_object({}) do |unit, hash|
        unit.names.each { |name| hash[name.to_s] = unit }
      end
    end

    def unit_names
      units.map(&:name).sort
    end

    def unit_names_with_aliases
      units.flat_map(&:names).sort
    end

    def unit_name_to_unit(name)
      unit_with_name_and_aliases[name.to_s]
    end

    def defined?(name)
      unit = unit_for(name)
      unit ? unit.name == name.to_s : false
    end

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

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
unit_measurements-3.2.0 lib/unit_measurements/unit_group.rb
unit_measurements-3.1.0 lib/unit_measurements/unit_group.rb
unit_measurements-3.0.0 lib/unit_measurements/unit_group.rb
unit_measurements-2.6.2 lib/unit_measurements/unit_group.rb
unit_measurements-2.6.1 lib/unit_measurements/unit_group.rb
unit_measurements-2.6.0 lib/unit_measurements/unit_group.rb
unit_measurements-2.5.0 lib/unit_measurements/unit_group.rb
unit_measurements-2.4.0 lib/unit_measurements/unit_group.rb
unit_measurements-2.3.0 lib/unit_measurements/unit_group.rb
unit_measurements-2.2.0 lib/unit_measurements/unit_group.rb
unit_measurements-2.1.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.7.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.6.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.5.1 lib/unit_measurements/unit_group.rb
unit_measurements-1.5.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.4.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.3.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.2.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.1.0 lib/unit_measurements/unit_group.rb
unit_measurements-1.0.0 lib/unit_measurements/unit_group.rb