Class: Colorit::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/colorit/command.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Command

Returns a new instance of Command.

Parameters:

  • Colorit::Config

    config



8
9
10
# File 'lib/colorit/command.rb', line 8

def initialize(config)
  @config = config
end

Instance Method Details

#parse_optionsObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/colorit/command.rb', line 12

def parse_options
  OptionParser.new do |opts|
    opts.banner = "Usage: colorit [options]"

    # add a CLI option to every color
    Colorit::Colors.each do |key,color|
      opts.on("-#{key.to_s[0]}", "--#{key} WORD", "highlight WORD in #{color}#{key}#{Colorit::Colors.reset()}") do |word|
        @config.send(key, word)
      end
    end

    opts.on('--debug', 'show debug output') do
      @config.debug = true
    end

    opts.on_tail("--version", "show version") do
      puts Colorit::VERSION.join('.')
      exit
    end
  end.parse!
end

#run(input, output) ⇒ Object

run the command line tool on the stream_source (ARGF in most cases)



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/colorit/command.rb', line 36

def run(input, output)
  colors = prepare_patterns if output.tty?

  if @config.debug?
    output.puts "DEBUG: using patterns:"
    output.puts(pretty_patterns)
  end


  begin
    input.each do |line|
      if output.tty?
        colors.each do |color, pattern|
          line = line.colorize(pattern, color)
        end
      end

      output.puts line
    end
  rescue SystemExit, Interrupt
    # do nothing but leaving the loop to exit ...
  end
end