Class: Mutter::Mutterer

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj = {}) ⇒ Mutterer

Returns a new instance of Mutterer.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mutter.rb', line 18

def initialize obj = {}
  @active, @styles = [], {}
  load File.dirname(__FILE__) + "/defaults"
  
  case obj
    when Hash
      obj = obj.inject({}) do |h, (k, v)|
        h.merge k => 
          (v.is_a?(Hash) ? v : { :match => v, :style => [k].flatten })
      end
      @styles.merge! obj
    when Array
      @active = obj
    when Symbol
      self.<< obj
    when String
      load obj
    else raise ArgumentError
  end
end

Class Method Details

.streamObject



96
97
98
# File 'lib/mutter.rb', line 96

def self.stream
  @stream
end

.stream=(io) ⇒ Object



100
101
102
# File 'lib/mutter.rb', line 100

def self.stream= io
  @stream = io
end

Instance Method Details

#<<(style) ⇒ Object



64
65
66
# File 'lib/mutter.rb', line 64

def << style
  @active << style
end

#esc(style) ⇒ Object



92
93
94
# File 'lib/mutter.rb', line 92

def esc style
  "\e#{style}\e"
end

#load(styles) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/mutter.rb', line 39

def load styles
  styles += '.yml' unless styles =~ /\.ya?ml/
  styles = YAML.load_file(styles).inject({}) do |h, (key, value)|
    value = { :match => value['match'], :style => value['style'] }
    h.merge key.to_sym => value
  end
  @styles.merge! styles
end

#parse(string) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/mutter.rb', line 68

def parse string
  @styles.inject(string) do |str, (name, options)|
    glyph, styles = options[:match], options[:style]
    if glyph.is_a? Array
      str.gsub(/#{Regexp.escape(glyph.first)}(.+?)
                #{Regexp.escape(glyph.last)}/x) { stylize $1, styles }
    else
      str.gsub(/(#{Regexp.escape(glyph)}+)(.+?)\1/) { stylize $2, styles }
    end
  end
end

#say(str, *styles) ⇒ Object Also known as: print



48
49
50
51
52
# File 'lib/mutter.rb', line 48

def say str, *styles
  out = stylize(parse(str), @active + styles)
  self.class.stream.write out.gsub(/\e(\d+)\e/, "\e[\\1m") + "\n"
  self.class.stream.flush
end

#stylize(string, styles = []) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/mutter.rb', line 80

def stylize string, styles = []
  [styles].flatten.inject(string) do |str, style|
    style = style.to_sym
    if ANSI.include? style
      open, close = ANSI[style]
      "#{esc(open)}#{str}#{esc(close || 0)}"
    else
      stylize(str, @styles[style][:style])
    end
  end
end

#watchObject



55
56
57
58
59
60
61
62
# File 'lib/mutter.rb', line 55

def watch
  begin
    yield
  rescue Interrupt
    puts
    exit 0
  end
end