Use Pry::Output to strip color when necessary

All credit to johnny5- for this idea:
952568b933

Pros: No longer need to check _pry_.config.color everywhere.
      All color is stripped (not just that added by pry)

Cons: Inefficient to add colors and then remove them again.
This commit is contained in:
Conrad Irwin 2014-05-01 01:10:10 -07:00
parent dd5e2511f3
commit 5d7c887129
5 changed files with 46 additions and 8 deletions

View File

@ -170,3 +170,4 @@ require "pry/last_exception"
require "pry/prompt"
require "pry/inspector"
require 'pry/object_path'
require 'pry/output'

View File

@ -21,11 +21,11 @@ class Pry
COLORS.each_pair do |color, value|
define_method color do |text|
Pry.config.color ? "\033[0;#{30+value}m#{text}\033[0m" : text.to_s
"\033[0;#{30+value}m#{text}\033[0m"
end
define_method "bright_#{color}" do |text|
Pry.config.color ? "\033[1;#{30+value}m#{text}\033[0m" : text.to_s
"\033[1;#{30+value}m#{text}\033[0m"
end
end
@ -38,12 +38,11 @@ class Pry
end
# Returns _text_ as bold text for use on a terminal.
# _Pry.config.color_ must be true for this method to perform any transformations.
#
# @param [String, #to_s] text
# @return [String] _text_
def bold(text)
Pry.config.color ? "\e[1m#{text}\e[0m" : text.to_s
"\e[1m#{text}\e[0m"
end
# Returns `text` in the default foreground colour.

31
lib/pry/output.rb Normal file
View File

@ -0,0 +1,31 @@
class Pry
class Output
attr_reader :_pry_
def initialize(_pry_)
@_pry_ = _pry_
end
def puts(str)
print "#{str.chomp}\n"
end
def print str
if _pry_.config.color
_pry_.config.output.print str
else
_pry_.config.output.print Helpers::Text.strip_color str
end
end
alias << print
alias write print
def method_missing(name, *args, &block)
_pry_.config.output.send(name, *args, &block)
end
def respond_to_missing?(*a)
_pry_.config.respond_to?(*a)
end
end
end

View File

@ -50,11 +50,11 @@ class Pry::Pager
# @param [#<<] output ($stdout) An object to send output to.
def best_available
if !_pry_.config.pager
NullPager.new(_pry_.config.output)
NullPager.new(_pry_.output)
elsif !SystemPager.available? || Pry::Helpers::BaseHelpers.jruby?
SimplePager.new(_pry_.config.output)
SimplePager.new(_pry_.output)
else
SystemPager.new(_pry_.config.output)
SystemPager.new(_pry_.output)
end
end
@ -107,7 +107,7 @@ class Pry::Pager
if @tracker.page?
@out.print "\n"
@out.print "\e[0m" if Pry.config.color
@out.print "\e[0m"
@out.print "<page break> --- Press enter to continue " \
"( q<enter> to break ) --- <page break>\n"
raise StopPaging if Readline.readline("").chomp == "q"

View File

@ -603,6 +603,13 @@ class Pry
Pry::Pager.new(self)
end
# Returns an output device
# @example
# _pry_.output.puts "ohai!"
def output
Pry::Output.new(self)
end
# Raise an exception out of Pry.
#
# See Kernel#raise for documentation of parameters.