module MetricFu::Utility

Constants

ESCAPE_CODES_PATTERN

Public Instance Methods

binread(file) click to toggle source
# File lib/metric_fu/utility.rb, line 50
def binread(file)
  File.binread(file)
end
capture_output(stream = STDOUT) { || ... } click to toggle source

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

# 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) click to toggle source

Removes non-ASCII characters

# 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) click to toggle source
# File lib/metric_fu/utility.rb, line 42
def glob(*args)
  Dir.glob(*args)
end
load_yaml(file) click to toggle source
# File lib/metric_fu/utility.rb, line 46
def load_yaml(file)
  YAML.load_file(file)
end
mkdir_p(*args) click to toggle source
# File lib/metric_fu/utility.rb, line 38
def mkdir_p(*args)
  FileUtils.mkdir_p(*args)
end
rm_rf(*args) click to toggle source
# File lib/metric_fu/utility.rb, line 34
def rm_rf(*args)
  FileUtils.rm_rf(*args)
end
stringify_keys(hash) click to toggle source
# 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) click to toggle source
# File lib/metric_fu/utility.rb, line 30
def strip_escape_codes(text)
  text.gsub(ESCAPE_CODES_PATTERN, "")
end