Module: CommandKit::Open

Includes:
Printing, Stdio
Defined in:
lib/command_kit/open.rb

Overview

Adds helper methods for opening files.

Features

  • Prints No such file or directory error if the given file does not exist.
  • Handles - file paths which indicate input should be read from STDIN or output written to STDOUT.

Examples

include CommandKit::Open

def run(path)
  open(path) do |file|
    # ...
  end
end

Since:

  • 0.6.0

Constant Summary

Constants included from Printing

Printing::EOL

Instance Method Summary collapse

Methods included from Printing

#print_error, #print_exception

Methods included from Stdio

#abort, #gets, #initialize, #print, #printf, #putc, #puts, #readline, #readlines, #stderr, #stdin, #stdout

Instance Method Details

#open(path, mode = 'r') {|file| ... } ⇒ File, ...

Opens a file for reading or writing.

Examples:

Opening a file for reading:

open(path)
# => #<File:...>

Temporarily opening a file for reading:

open(path) do |file|
  # ...
end

Opening a file for writing:

open(path,'w')
# => #<File:...>

Temporarily opening a file for writing:

open(path,'w') do |output|
  output
end

Parameters:

  • path (String)

    The path of the given file. May be "-" to indicate that input should be read from STDINT or output written to STDOUT.

  • mode (String) (defaults to: 'r')

    The mode to open the file with.

Yields:

  • (file)
    • If the given path is "-".
      • and the given mode contains w or a, then Stdio#stdout will be yielded.
      • and no mode is given or if the mode contains r, then Stdio#stdin will be yielded.
    • Otherwise, the newly opened file.

Yield Parameters:

Returns:

  • (File, IO, Object)
    • If no block is given, the newly opened file, or Stdio#stdin / Stdio#stdout if the given path is "-", will be returned.
    • If a block was given, then the return value of the block will be returned.

Since:

  • 0.6.0



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/command_kit/open.rb', line 82

def open(path,mode='r',&block)
  if path == '-'
    io = case mode
         when /[wa]/ then stdout
         else             stdin
         end

    if block_given?
      return yield(io)
    else
      return io
    end
  end

  begin
    File.open(path,mode,&block)
  rescue Errno::ENOENT
    print_error "No such file or directory: #{path}"
    exit(1)
  end
end