Skip to content

Commit

Permalink
allow X11 color methods using refinement interface
Browse files Browse the repository at this point in the history
  • Loading branch information
tobyh committed Oct 22, 2023
1 parent 629cde5 commit add1f75
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 45 deletions.
49 changes: 4 additions & 45 deletions lib/rainbow/presenter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,55 +89,14 @@ def cross_out

alias strike cross_out

def black
color(:black)
end

def red
color(:red)
end

def green
color(:green)
end

def yellow
color(:yellow)
end

def blue
color(:blue)
end

def magenta
color(:magenta)
end

def cyan
color(:cyan)
end

def white
color(:white)
end

# We take care of X11 color method call here.
# Such as #aqua, #ghostwhite.
def method_missing(method_name, *args)
if Color::X11Named.color_names.include?(method_name) && args.empty?
color(method_name)
else
super
end
end

def respond_to_missing?(method_name, *args)
Color::X11Named.color_names.include?(method_name) && args.empty? || super
# Define foreground named color methods eg #red and #tomato
(Color::Named.color_names | Color::X11Named.color_names).each do |name|
define_method(name) { color(name) }
end

private

def wrap_with_sgr(codes) #:nodoc:
def wrap_with_sgr(codes) # :nodoc:
self.class.new(StringUtils.wrap_with_sgr(self, [*codes]))
end
end
Expand Down
9 changes: 9 additions & 0 deletions spec/integration/refinement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
RSpec.describe 'Rainbow refinement' do
before do
require 'rainbow/refinement'
Rainbow.enabled = true

class ScopeNotIncluded
def self.red_hello
Expand All @@ -16,6 +17,10 @@ class ScopeIncluded
def self.red_hello
'hello'.red
end

def self.tomato_hello
'hello'.tomato
end
end
end

Expand All @@ -29,6 +34,10 @@ def self.red_hello
expect(ScopeIncluded.red_hello).to eq(Rainbow('hello').red)
end

it 'provides X11 named color methods' do
expect(ScopeIncluded.tomato_hello).to eq(Rainbow('hello').tomato)
end

it 'respects disabled state' do
Rainbow.enabled = false
expect(ScopeIncluded.red_hello).to eq('hello')
Expand Down

0 comments on commit add1f75

Please sign in to comment.