Class: EpoOps::Util

Inherits:
Object
  • Object
show all
Defined in:
lib/epo_ops/util.rb

Class Method Summary collapse

Class Method Details

.dig(data, *path) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/epo_ops/util.rb', line 24

def self.dig(data,*path)
  path.flatten.inject(data) do |d,key|
    if d.is_a? Hash
      d[key]
    else
      nil
    end
  end
end

.find_in_data(epo_hash, path) ⇒ Object

the path should be an array of strings indicating the path you want to go in the hash



4
5
6
# File 'lib/epo_ops/util.rb', line 4

def self.find_in_data(epo_hash, path)
  path.reduce(epo_hash) { |res, c| parse_hash_flat(res, c) }
end

.flat_dig(data, *path) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/epo_ops/util.rb', line 34

def self.flat_dig(data,*path)
  path.flatten.inject(data) do |d,key|
    if d.is_a? Hash
      d[key].is_a?(Array) ? d[key] : [d[key]]
    elsif d.is_a? Array
      d.select {|element| element.is_a? Hash}.flat_map {|element| element[key]}
    else
      []
    end
  end.reject(&:nil?)
end

.parse_change_gazette_num(num) ⇒ Object



46
47
48
49
50
# File 'lib/epo_ops/util.rb', line 46

def self.parse_change_gazette_num(num)
  res = /^(?<year>\d{4})\/(?<week>\d{2})$/.match(num)
  return nil if res.nil?
  Date.commercial(Integer(res[:year], 10), Integer(res[:week], 10))
end

.parse_hash_flat(hash_layer, target) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/epo_ops/util.rb', line 8

def self.parse_hash_flat(hash_layer, target)
  result = []
  if hash_layer.nil?
    return []
  elsif hash_layer.class == String
    return []
  elsif hash_layer.class == Array
    result.concat(hash_layer.map { |x| parse_hash_flat(x, target) })
  elsif hash_layer[target]
    result << hash_layer[target]
  elsif hash_layer.class == Hash || hash_layer.respond_to?(:to_h)
    result.concat(hash_layer.to_h.map { |_x, y| parse_hash_flat(y, target) })
  end
  result.flatten
end