Module: CMF::Dictionary

Defined in:
lib/cmf/dictionary.rb

Overview

Provides functionality for validating the dictionary argument passed to Builder and Parser.

Class Method Summary collapse

Class Method Details

.validate(dictionary) ⇒ Hash

Validates a dictionary, and optionally converts it from array form to hash form.

Raises:

  • (TypeError)

    if any dictionary keys are integers.

  • (TypeError)

    if any dictionary values are not integers.

  • (ArgumentError)

    if dictionary values are not unique.

  • (ArgumentError)

    if any dictionary values are negative.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cmf/dictionary.rb', line 25

def self.validate(dictionary)
  return {} if dictionary.nil?

  if dictionary.is_a? Array
    dictionary = dictionary.map.with_index {|s, i| [s, i]}.to_h
  end

  dictionary.is_a? Hash or raise TypeError, "Dictionary must be an Array or Hash"
  dictionary.keys.each do |k|
    !k.is_a?(Integer) or raise TypeError, "Invalid dictionary key #{k}. Must not be an integer"
  end
  dictionary.values.each do |v|
    v.is_a?(Integer) or raise TypeError, "Invalid dictionary value #{v}. Must all be an integer"
    v >= 0 or raise ArgumentError, "Invalid dictionary value #{v}. Must be >= 0"
  end
  dictionary.values.size == dictionary.values.uniq.size or raise ArgumentError, "Dictionary values must be unique"

  dictionary
end