Module: Kennel::Utils

Defined in:
lib/kennel/utils.rb

Class Method Summary collapse

Class Method Details

.all_keys(items) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/kennel/utils.rb', line 57

def all_keys(items)
  case items
  when Hash then items.keys + items.values.flat_map { |v| all_keys(v) }
  when Array then items.flat_map { |i| all_keys(i) }
  else []
  end
end

.capture_sh(command) ⇒ Object



9
10
11
12
13
# File 'lib/kennel/utils.rb', line 9

def capture_sh(command)
  result = `#{command} 2>&1`
  raise "Command failed:\n#{command}\n#{result}" unless $CHILD_STATUS.success?
  result
end

.natural_order(name) ⇒ Object



43
44
45
# File 'lib/kennel/utils.rb', line 43

def natural_order(name)
  name.split(/(\d+)/).each_with_index.map { |x, i| i.odd? ? x.to_i : x }
end

.parallel(items, max: 10) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/kennel/utils.rb', line 20

def parallel(items, max: 10)
  threads = [items.size, max].min
  work = items.each_with_index.to_a
  done = Array.new(items.size)
  workers = Array.new(threads).map do
    Thread.new do
      loop do
        item, i = work.pop
        break unless i
        done[i] =
          begin
            yield item
          rescue Exception => e # rubocop:disable Lint/RescueException
            work.clear
            e
          end
      end
    end
  end
  workers.each(&:join)
  done.each { |d| raise d if d.is_a?(Exception) }
end

.path_to_url(path) ⇒ Object



15
16
17
18
# File 'lib/kennel/utils.rb', line 15

def path_to_url(path)
  subdomain = (ENV["DATADOG_SUBDOMAIN"] || "app")
  "https://#{subdomain}.datadoghq.com#{path}"
end

.presence(value) ⇒ Object



5
6
7
# File 'lib/kennel/utils.rb', line 5

def presence(value)
  value.nil? || value.empty? ? nil : value
end

.retry(*errors, times:) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/kennel/utils.rb', line 47

def retry(*errors, times:)
  yield
rescue *errors => e
  times -= 1
  raise if times < 0
  Kennel.err.puts "Error #{e}, #{times} retries left"
  retry
end