Module: MetricFu::Io

Included in:
Formatter::HTML, Formatter::YAML
Defined in:
lib/metric_fu/io.rb

Defined Under Namespace

Modules: FileSystem

Instance Method Summary collapse

Instance Method Details

#dir_for(path) ⇒ Object



120
121
122
123
124
125
# File 'lib/metric_fu/io.rb', line 120

def dir_for(path)
  return nil if path.nil?
  pathname = path_relative_to_base(path)
  MetricFu::Utility.mkdir_p(pathname) unless File.directory?(pathname)
  pathname
end

#file_for(path, &block) ⇒ Object



114
115
116
117
118
# File 'lib/metric_fu/io.rb', line 114

def file_for(path, &block)
  File.open(path_relative_to_base(path), "w") do |file|
    block.call(file)
  end
end

#io_for(path_or_io) {|IO| ... } ⇒ Object

Note:

Given a path to a file, an open file will be yielded and closed after the block completes. Given an existing io stream, the stream will not be automatically closed. Cleanup, if necessary, is the responsibility of the caller.

Yields an io object for writing output.

Examples:

io_for('path/to/file') do |io|
  io.write(output)
end

io_for(STDOUT) do |io|
  io.write(output)
end

stream = StringIO.new
io_for(stream) do |io|
  io.write(output)
end

Parameters:

  • path_or_io (String, #to_s, IO, #write)

    a file path or an io stream that responds to write.

Yields:

  • (IO)

    an open stream for writing.

Raises:

  • (ArgumentError)


102
103
104
105
106
107
108
109
110
111
112
# File 'lib/metric_fu/io.rb', line 102

def io_for(path_or_io, &block)
  raise ArgumentError, "No path or io provided." if path_or_io.nil?
  raise ArgumentError, "No block given. Cannot yield io stream." unless block_given?

  if path_or_io.respond_to?(:write)
    # We have an existing open stream...
    block.call(path_or_io)
  else # Otherwise, we assume its a file path...
    file_for(path_or_io, &block)
  end
end

#path_relative_to_base(path) ⇒ Object



127
128
129
130
# File 'lib/metric_fu/io.rb', line 127

def path_relative_to_base(path)
  pathname = MetricFu.run_path.join(MetricFu::Io::FileSystem.directory("base_directory")) # make full path relative to base directory
  pathname.join(path)
end

#write_output(output, path_or_io) ⇒ nil

Writes the output to a file or io stream.

Parameters:

  • output (String, #to_s)

    the content to write.

  • path_or_io (String, #to_s, IO, #write)

    a file path or an io stream that responds to write.

Returns:

  • (nil)


71
72
73
74
75
# File 'lib/metric_fu/io.rb', line 71

def write_output(output, path_or_io)
  io_for(path_or_io) do |io|
    io.write(output)
  end
end