Class: Tefil::TextFilterBase

Inherits:
Object
  • Object
show all
Defined in:
lib/tefil/textfilterbase.rb

Overview

Module that provide a framework for text filters.

Provide basic functions for a command like below:

Input:
  - Without indicating filenames like "command.rb",
    input data is eaten from STDIN.
  - With indicating filenames like "command.rb *.txt",
    input data is eaten from indicated files in order.
    When the file which is in the filenames does not exist,
    output report to STDERR.

Output:
  - Without indicating "--overwrite" option,
    output to STDOUT even from many files.
  - With indicating "--overwrite" option,
    - With indicating input files,
      overwrite each file.
    - Without indicating input files,
      output to STDOUT in one stream.

If indicated file(s) not found, this program notify on stderr and does not throw an exception.

Defined Under Namespace

Classes: NotRedefinedMethodError, TypeError

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ TextFilterBase

Returns a new instance of TextFilterBase.



36
37
38
39
# File 'lib/tefil/textfilterbase.rb', line 36

def initialize(options = {})
  @overwrite = options[:overwrite]
  @smart_filename = options[:smart_filename]
end

Instance Method Details

#filter(filenames) ⇒ Object

line ごとのファイル名表示はここでは提供せず、したければ process_stream で作る。 grep の行数表示のように、複雑な表示をすることもありうる。



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/tefil/textfilterbase.rb', line 57

def filter(filenames)
  @num_files = filenames.size
  input_io = $stdin
  output_io = $stdout
  if filenames.size == 0 
    process_stream( input_io, output_io)
  else
    filenames.each do |filename|
      @filename = filename
      input_io = File.open(filename, "r")
      output_io = Tempfile.new("tefil", "/tmp") if @overwrite
      smart_filename(output_io)
      begin
        process_stream(input_io, output_io)
      rescue ArgumentError, Errno::EISDIR
        $stderr.puts $!
        next
      rescue Errno::EPIPE
      end

      if @overwrite
        output_io.open
        File.open(filename, "w") do |overwrite_io|
          output_io.each { |line| overwrite_io.puts(line) }
        end
      end
    end
  end
end