Sha256: 766d0bfecb3c64df4a7cb8be0b0a3d7df9b8571b57ed08d4457a51425048ff71

Contents?: true

Size: 934 Bytes

Versions: 3

Compression:

Stored size: 934 Bytes

Contents

class Measured::UnitSystemBuilder
  def initialize(case_sensitive: false)
    @units = []
    @case_sensitive = case_sensitive
  end

  def unit(unit_name, aliases: [], value: nil)
    @units << build_unit(unit_name, aliases: aliases, value: value)
    nil
  end

  def build
    unit_system_class.new(@units)
  end

  private

  def build_unit(name, aliases: [], value: nil)
    unit = unit_class.new(name, aliases: aliases, value: value)
    check_for_duplicate_unit_names!(unit)
    unit
  end

  def unit_class
    @case_sensitive ? Measured::Unit : Measured::CaseInsensitiveUnit
  end

  def unit_system_class
    @case_sensitive ? Measured::UnitSystem : Measured::CaseInsensitiveUnitSystem
  end

  def check_for_duplicate_unit_names!(unit)
    names = @units.flat_map(&:names)
    if names.any? { |name| unit.names.include?(name) }
      raise Measured::UnitError, "Unit #{unit.name} has already been added."
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
measured-2.0.0.pre3 lib/measured/unit_system_builder.rb
measured-2.0.0.pre2 lib/measured/unit_system_builder.rb
measured-2.0.0.pre1 lib/measured/unit_system_builder.rb