From 39bf45e4d524e6e5beaad446ef21e3591c57dcb5 Mon Sep 17 00:00:00 2001 From: Mike Dvorkin Date: Mon, 3 Sep 2012 17:26:27 -0700 Subject: [PATCH] Enabled peaceful coexistence with the colorize gem --- lib/awesome_print/formatter.rb | 15 ++++++++++---- spec/misc_specs.rb | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/lib/awesome_print/formatter.rb b/lib/awesome_print/formatter.rb index a639168..98fb6df 100755 --- a/lib/awesome_print/formatter.rb +++ b/lib/awesome_print/formatter.rb @@ -39,12 +39,19 @@ module AwesomePrint # Pick the color and apply it to the given string as necessary. #------------------------------------------------------------------------------ - def colorize(s, type) - s = CGI.escapeHTML(s) if @options[:html] + def colorize(str, type) + str = CGI.escapeHTML(str) if @options[:html] if @options[:plain] || !@options[:color][type] || !@inspector.colorize? - s + str + # + # Check if the string color method is defined by awesome_print and accepts + # html parameter or it has been overriden by some gem such as colorize. + # + elsif str.method(@options[:color][type]).arity == -1 # Accepts html parameter. + str.send(@options[:color][type], @options[:html]) else - s.send(@options[:color][type], @options[:html]) + str = %Q|#{str}| if @options[:html] + str.send(@options[:color][type]) end end diff --git a/spec/misc_specs.rb b/spec/misc_specs.rb index 3cc6942..f438276 100644 --- a/spec/misc_specs.rb +++ b/spec/misc_specs.rb @@ -101,5 +101,43 @@ EOS } EOS end + + describe "Coexistence with the colorize gem" do + before do # Redefine String#red just like colorize gem does it. + @awesome_method = "".method(:red) + String.instance_eval do + define_method :red do # Method arity is 0. + "[red]#{self}[/red]" + end + end + end + + after do # Restore String#red method. + awesome_method = @awesome_method + String.instance_eval do + define_method :red, awesome_method + end + end + + it "shoud not raise ArgumentError when formatting HTML" do + out = "hello".ai(:color => { :string => :red }, :html => true) + out.should == %Q|
[red]"hello"[/red]
| + end + + it "shoud not raise ArgumentError when formatting HTML (shade color)" do + out = "hello".ai(:color => { :string => :redish }, :html => true) + out.should == %Q|
"hello"
| + end + + it "shoud not raise ArgumentError when formatting non-HTML" do + out = "hello".ai(:color => { :string => :red }, :html => false) + out.should == %Q|[red]"hello"[/red]| + end + + it "shoud not raise ArgumentError when formatting non-HTML (shade color)" do + out = "hello".ai(:color => { :string => :redish }, :html => false) + out.should == %Q|\e[0;31m"hello"\e[0m| + end + end end end