From cf12a726ebe26ee5169c14316af5dfe303af7c6d Mon Sep 17 00:00:00 2001 From: tobyh Date: Sun, 22 Oct 2023 15:31:24 +1100 Subject: [PATCH] allow X11 color methods using refinement interface --- lib/rainbow/presenter.rb | 49 +++-------------------------- spec/integration/refinement_spec.rb | 9 ++++++ 2 files changed, 13 insertions(+), 45 deletions(-) diff --git a/lib/rainbow/presenter.rb b/lib/rainbow/presenter.rb index 753f273..5a391f2 100644 --- a/lib/rainbow/presenter.rb +++ b/lib/rainbow/presenter.rb @@ -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 diff --git a/spec/integration/refinement_spec.rb b/spec/integration/refinement_spec.rb index 2aa3a9e..56fb7a5 100644 --- a/spec/integration/refinement_spec.rb +++ b/spec/integration/refinement_spec.rb @@ -4,6 +4,7 @@ RSpec.describe 'Rainbow refinement' do before do require 'rainbow/refinement' + Rainbow.enabled = true class ScopeNotIncluded def self.red_hello @@ -16,6 +17,10 @@ class ScopeIncluded def self.red_hello 'hello'.red end + + def self.tomato_hello + 'hello'.tomato + end end end @@ -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')