aboutsummaryrefslogtreecommitdiff
path: root/lib/cobalt.rb
blob: bcd683c020b7c91eb16601e9584ca85945113b73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
require 'rubygems'
require 'isna'
require 'logger'

module Cobalt

  class Console

    attr_accessor :separator_length

    def initialize( options = {} )
      @indent           = 0
      @loggers          = options[:loggers] || [::Logger.new(STDOUT)]
      @separator_length = 120
      @color            = :white
    end

    def add_logger logger
      @loggers << logger
    end

    def remove_logger logger
      @loggers = @loggers - [logger]
    end

    def log(*objects)
      objects.each do |object|
        the_string = object.to_s
        the_string = the_string.to_ansi.send(@color).to_s
        the_string = the_string.gsub(/^/, ' ' * @indent)
        @loggers.each { |logger| logger.info(the_string) }
      end
      self
    end

    def pp(*objects)
      dump = ""
      if objects.size > 1
        PP.pp(objects, dump)
      else
        PP.pp(objects.first, dump)
      end
      log(dump)
    end

    def info(*objects)
      notice(*objects)
    end

    def notice(*objects)
      color(:cyan) { log(*objects) }
    end

    def warn(*objects)
      color(:yellow) { log(*objects) }
    end

    def error(*objects)
      color(:red) { log(*objects) }
    end

    def separator(type = '-')
      log((type * (@separator_length - @indent)))
    end

    def space(lines = 1)
      lines.times { self.log('') }
      self
    end

    def indent
      if block_given?
        @indent = @indent + 2
        yield
        @indent = @indent - 2
      else
        @indent = @indent + 2
      end
      self
    end

    def outdent
      @indent = @indent - 2
      self
    end

    def color(symbol)
      if block_given?
        old = @color
        @color = symbol
        yield
        @color = old
      else
        @color = symbol
      end
      self
    end

  end

end