Module: Apportion::Util

Included in:
Apportion
Defined in:
lib/apportion/util.rb

Overview

Utility methods

Class Method Summary collapse

Class Method Details

.file_read_json_to_hash(path_to_directory, json_file_name) ⇒ Hash

Reads a JSON file and returns a hash with symbols as keys

Examples:

file_read_json_to_hash(path_to_directory, json_file_name)
# => {a: 5, b: 2, c: 3}

Parameters:

  • path_to_directory (String)
  • json_file_name (String)

Returns:

  • (Hash)

    with symbolized keys



15
16
17
18
# File 'lib/apportion/util.rb', line 15

def file_read_json_to_hash(path_to_directory, json_file_name)
  hash = JSON.parse(File.read(File.join(path_to_directory, json_file_name)))
  symbolize_keys(hash)
end

.hash_values_sum(hash) ⇒ Numeric

Sums all of the values in a hash

Examples:

hash_values_sum({a: 8, b: 2, c: 3})
# => 13

Parameters:

  • hash (Hash)

    with numeric values

Returns:

  • (Numeric)

    the sum of all values



28
29
30
# File 'lib/apportion/util.rb', line 28

def hash_values_sum(hash)
  hash.values.reduce(0) { |acc, v| acc + v }
end

.symbolize_keys(hash) ⇒ Hash

Returns a new hash with symbols as keys

Examples:

symbolize_keys({'a' =>  0, 'b' => '2', c: '3'})
# => {a: 0, b: '2', c: '3'}

Parameters:

  • hash (Hash)

Returns:

  • (Hash)

    a new hash with all string keys converted to symbols, provided that the keys respond to #to_sym

See Also:

  • rails activesupport/lib/active_support/core_ext/hash/keys.rb


42
43
44
# File 'lib/apportion/util.rb', line 42

def symbolize_keys(hash)
  transform_keys(hash) { |key| key.to_sym rescue key }
end