Module: Kennel::Utils

Defined in:
lib/kennel/utils.rb

Defined Under Namespace

Classes: TeeIO

Class Method Summary collapse

Class Method Details

.ask(question) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/kennel/utils.rb', line 26

def ask(question)
  printf color(:red, "#{question} -  press 'y' to continue: ")
  begin
    STDIN.gets.chomp == "y"
  rescue Interrupt # do not show a backtrace if user decides to Ctrl+C here
    printf "\n"
    exit 1
  end
end

.capture_sh(command) ⇒ Object



64
65
66
67
68
# File 'lib/kennel/utils.rb', line 64

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

.capture_stdoutObject



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

def capture_stdout
  old = $stdout
  $stdout = StringIO.new
  yield
  $stdout.string
ensure
  $stdout = old
end

.color(color, text) ⇒ Object



36
37
38
39
# File 'lib/kennel/utils.rb', line 36

def color(color, text)
  code = { red: 31, green: 32, yellow: 33 }.fetch(color)
  "\e[#{code}m#{text}\e[0m"
end

.parallel(items) ⇒ Object



78
79
80
81
82
83
84
85
86
# File 'lib/kennel/utils.rb', line 78

def parallel(items)
  items.map do |item|
    Thread.new do
      yield item
    rescue StandardError => e
      e
    end
  end.map(&:value).each { |i| raise i if i.is_a?(StandardError) }
end

.path_to_url(path) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/kennel/utils.rb', line 70

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

.presence(value) ⇒ Object



22
23
24
# File 'lib/kennel/utils.rb', line 22

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

.snake_case(string) ⇒ Object



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

def snake_case(string)
  string.gsub(/::/, "_") # Foo::Bar -> foo_bar
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') # FOOBar -> foo_bar
    .gsub(/([a-z\d])([A-Z])/, '\1_\2') # fooBar -> foo_bar
    .downcase
end

.strip_shell_control(text) ⇒ Object



41
42
43
# File 'lib/kennel/utils.rb', line 41

def strip_shell_control(text)
  text.gsub(/\e\[\d+m(.*?)\e\[0m/, "\\1").gsub(/.#{Regexp.escape("\b")}/, "")
end

.tee_stdoutObject



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

def tee_stdout
  old = $stdout
  string = StringIO.new
  $stdout = TeeIO.new([$stdout, string])
  yield
  string.string
ensure
  $stdout = old
end