Module: Ripl::ColorStreams

Defined in:
lib/ripl/color_streams.rb

Constant Summary collapse

VERSION =
'0.1.2'
COLORS =
{
  :nothing      => '0;0',
  :black        => '0;30',
  :red          => '0;31',
  :green        => '0;32',
  :brown        => '0;33',
  :blue         => '0;34',
  :purple       => '0;35',
  :cyan         => '0;36',
  :light_gray   => '0;37',
  :dark_gray    => '1;30',
  :light_red    => '1;31',
  :light_green  => '1;32',
  :yellow       => '1;33',
  :light_blue   => '1;34',
  :light_purple => '1;35',
  :light_cyan   => '1;36',
  :white        => '1;37',
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.patch_stream(stream_name) ⇒ Object

patch stream output (but do not activate)



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ripl/color_streams.rb', line 55

def patch_stream(stream_name)
  stream = Object.const_get stream_name.to_s.upcase

  stream.instance_eval do
    alias real_write write
    def color_write(*args) # define_method is not defined for singletons :/
      stream_name = (self == $stdout) ? :stdout : :stderr
      Ripl::ColorStreams.write_stream stream_name, *args
    end
  end
end

.set_stream_status(stream_name, true_or_false) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/ripl/color_streams.rb', line 67

def set_stream_status(stream_name, true_or_false)
  stream = Object.const_get stream_name.to_s.upcase

  # check if stream object has changed
  unless stream.respond_to?(:real_write) && stream.respond_to?(:color_write)
    Ripl::ColorStreams.patch_stream stream_name
  end

  # (de)activate
  if true_or_false
    stream.instance_eval do alias write color_write end
  else
    stream.instance_eval do alias write real_write  end
  end
end

.write_stream(stream_name, data) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/ripl/color_streams.rb', line 45

def write_stream(stream_name, data)
  stream = Object.const_get stream_name.to_s.upcase
  color_config = Ripl.config[ ('color_streams_' + stream_name.to_s).to_sym ]
  color_code   = !color_config || color_config.to_s[/^[\d;]+$/] ?
    color_config : Ripl::ColorStreams::COLORS[color_config.to_sym]

  stream.real_write color_code ? "\e[#{ color_code }m#{ data }\e[0;0m" : data.to_s
end

Instance Method Details

#before_loopObject



26
27
28
29
30
31
32
33
# File 'lib/ripl/color_streams.rb', line 26

def before_loop
  # patch $stdout/$stderr
  Ripl::ColorStreams.patch_stream :stdout
  Ripl::ColorStreams.patch_stream :stderr

  # call ripl / next plugin
  super
end

#loop_eval(input) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/ripl/color_streams.rb', line 35

def loop_eval(input)
  Ripl::ColorStreams.set_stream_status :stdout, true
  Ripl::ColorStreams.set_stream_status :stderr, true
  super
ensure
  Ripl::ColorStreams.set_stream_status :stdout, false
  Ripl::ColorStreams.set_stream_status :stderr, false
end