Module: HighLine::StringExtensions

Included in:
String
Defined in:
lib/highline/string_extensions.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
# File 'lib/highline/string_extensions.rb', line 32

def self.included(base)
  HighLine::COLORS.each do |color|
    base.class_eval <<-END
      def #{color.downcase}
        color(:#{color.downcase})
      end
    END
    base.class_eval <<-END
      def on_#{color.downcase}
        on(:#{color.downcase})
      end
    END
    HighLine::STYLES.each do |style|
      base.class_eval <<-END
        def #{style.downcase}
          color(:#{style.downcase})
        end
      END
    end
  end
  
  base.class_eval do
    def color(*args)
      self.class.new(HighLine.color(self, *args))
    end
    alias_method :foreground, :color
    
    def on(arg)
      color(('on_' + arg.to_s).to_sym)
    end

    def uncolor
      self.class.new(HighLine.uncolor(self))
    end
    
    def rgb(*colors)
      color_code = colors.map{|color| color.is_a?(Numeric) ? '%02x'%color : color.to_s}.join
      raise "Bad RGB color #{colors.inspect}" unless color_code =~ /^[a-fA-F0-9]{6}/
      color("rgb_#{color_code}".to_sym)
    end
    
    def on_rgb(*colors)
      color_code = colors.map{|color| color.is_a?(Numeric) ? '%02x'%color : color.to_s}.join
      raise "Bad RGB color #{colors.inspect}" unless color_code =~ /^[a-fA-F0-9]{6}/
      color("on_rgb_#{color_code}".to_sym)
    end
    
    # TODO Chain existing method_missing
    def method_missing(method, *args, &blk)
      if method.to_s =~ /^(on_)?rgb_([0-9a-fA-F]{6})$/
        color(method)
      else
        raise NoMethodError, "undefined method `#{method}' for #<#{self.class}:#{'%#x'%self.object_id}>"
      end
    end
  end
end