Module: MetricFu::Utility

Defined in:
lib/metric_fu/utility.rb

Constant Summary collapse

ESCAPE_CODES_PATTERN =
Regexp.new('\e\[(?:\d;)?\d{1,2}m')

Class Method Summary collapse

Class Method Details

.binread(file) ⇒ Object



50
51
52
# File 'lib/metric_fu/utility.rb', line 50

def binread(file)
  File.binread(file)
end

.capture_output(stream = STDOUT, &_block) ⇒ Object

From episode 029 of Ruby Tapas by Avdi rubytapas.dpdcart.com/subscriber/post?id=88



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/metric_fu/utility.rb', line 56

def capture_output(stream = STDOUT, &_block)
  old_stdout = stream.clone
  pipe_r, pipe_w = IO.pipe
  pipe_r.sync    = true
  output         = ""
  reader = Thread.new do
    begin
      loop do
        output << pipe_r.readpartial(1024)
      end
    rescue EOFError
    end
  end
  stream.reopen(pipe_w)
  yield
ensure
  stream.reopen(old_stdout)
  pipe_w.close
  reader.join
  pipe_r.close
  return output
end

.clean_ascii_text(text) ⇒ Object

Removes non-ASCII characters



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/metric_fu/utility.rb', line 10

def clean_ascii_text(text)
  if text.respond_to?(:encode)
    # avoids invalid multi-byte escape error
    ascii_text = text.encode("ASCII", invalid: :replace, undef: :replace, replace: "")
    # see http://www.ruby-forum.com/topic/183413
    pattern = Regexp.new('[\x80-\xff]', nil, "n")
    ascii_text.gsub(pattern, "")
  else
    text
  end
end

.glob(*args) ⇒ Object



42
43
44
# File 'lib/metric_fu/utility.rb', line 42

def glob(*args)
  Dir.glob(*args)
end

.load_yaml(file) ⇒ Object



46
47
48
# File 'lib/metric_fu/utility.rb', line 46

def load_yaml(file)
  YAML.load_file(file)
end

.mkdir_p(*args) ⇒ Object



38
39
40
# File 'lib/metric_fu/utility.rb', line 38

def mkdir_p(*args)
  FileUtils.mkdir_p(*args)
end

.rm_rf(*args) ⇒ Object



34
35
36
# File 'lib/metric_fu/utility.rb', line 34

def rm_rf(*args)
  FileUtils.rm_rf(*args)
end

.stringify_keys(hash) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/metric_fu/utility.rb', line 22

def stringify_keys(hash)
  result = {}
  hash.each do |key, value|
    result[key.to_s] = value
  end
  result
end

.strip_escape_codes(text) ⇒ Object



30
31
32
# File 'lib/metric_fu/utility.rb', line 30

def strip_escape_codes(text)
  text.gsub(ESCAPE_CODES_PATTERN, "")
end