1
0
Fork 0
mirror of https://github.com/awesome-print/awesome_print synced 2023-03-27 23:22:34 -04:00

Added :html => true option to dump HTML colors rather that ANSI

This commit is contained in:
Mike Dvorkin 2011-05-07 11:50:04 -07:00
parent a9ec52c4b4
commit a861908fb7
5 changed files with 75 additions and 79 deletions

View file

@ -20,10 +20,11 @@ objects and usage within Rails templates are supported via included mixins.
Default options: Default options:
:multiline => true, # Display in multipe lines. :multiline => true, # Display in multiple lines.
:plain => false, # Use colors. :plain => false, # Use colors.
:indent => 4, # Indent using 4 spaces. :indent => 4, # Indent using 4 spaces.
:index => true, # Display array indices. :index => true, # Display array indices.
:html => false, # Use ANSI color codes rather than HTML.
:sorted_hash_keys => false, # Do not sort hash keys. :sorted_hash_keys => false, # Do not sort hash keys.
:color => { :color => {
:array => :white, :array => :white,
@ -131,7 +132,7 @@ Supported color names:
$ cat > 6.rb $ cat > 6.rb
require "ap" require "ap"
ap(42 == ap(42)) ap 42 == ap(42)
^D ^D
$ ruby 6.rb $ ruby 6.rb
42 42
@ -217,25 +218,30 @@ lines into your ~/.irbrc file:
end end
### Logger Convenience Method ### ### Logger Convenience Method ###
awesome_print adds an ap method to the Logger and ActiveSupport::BufferedLogger classes, awesome_print adds the 'ap' method to the Logger and ActiveSupport::BufferedLogger classes
allowing you to call: letting you call:
logger.ap object logger.ap object
By default, this logs at the :debug level. You can override that globally with By default, this logs at the :debug level. You can override that globally with:
:log_level => :info :log_level => :info
in the custom defaults (see below), or you can override on a per call basis with in the custom defaults (see below). You can also override on a per call basis with:
logger.ap object, :warn logger.ap object, :warn
### ActionView Convenience Method ### ### ActionView Convenience Method ###
awesome_print adds an ap method to the ActionView::Base class making it available awesome_print adds the 'ap' method to the ActionView::Base class making it available
within Rails templates. For example: within Rails templates. For example:
<%= ap @accounts.first %> <%= ap @accounts.first %>
With other web frameworks (ex: in Sinatra templates) you can explicitly request HTML
formatting:
<%= ap @accounts.first, :html => true %>
### Setting Custom Defaults ### ### Setting Custom Defaults ###
You can set your own default options by creating ``.aprc`` file in your home You can set your own default options by creating ``.aprc`` file in your home
directory. Within that file assign your defaults to ``AwesomePrint.defaults``. directory. Within that file assign your defaults to ``AwesomePrint.defaults``.
@ -278,7 +284,9 @@ For example:
### License ### ### License ###
Copyright (c) 2010-2011 Michael Dvorkin Copyright (c) 2010-2011 Michael Dvorkin
twitter.com/mid twitter.com/mid
%w(mike dvorkin.net) * "@" || %w(mike fatfreecrm.com) * "@" %w(mike dvorkin.net) * "@" || %w(mike fatfreecrm.com) * "@"
Released under the MIT license. See LICENSE file for details. Released under the MIT license. See LICENSE file for details.

View file

@ -3,19 +3,22 @@
# Awesome Print is freely distributable under the terms of MIT license. # Awesome Print is freely distributable under the terms of MIT license.
# See LICENSE file or http://www.opensource.org/licenses/mit-license.php # See LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
require "cgi"
require "shellwords" require "shellwords"
class AwesomePrint class AwesomePrint
AP = :__awesome_print__ unless defined?(AwesomePrint::AP) AP = :__awesome_print__ unless defined?(AwesomePrint::AP)
CORE = [ :array, :hash, :class, :file, :dir, :bigdecimal, :rational, :struct, :method, :unboundmethod ] unless defined?(AwesomePrint::CORE) CORE = [ :array, :hash, :class, :file, :dir, :bigdecimal, :rational, :struct, :method, :unboundmethod ] unless defined?(AwesomePrint::CORE)
@@force_colors = false
def initialize(options = {}) def initialize(options = {})
@options = { @options = {
:multiline => true, :multiline => true, # Display in multiple lines.
:plain => false, :plain => false, # Use colors.
:indent => 4, :indent => 4, # Indent using 4 spaces.
:index => true, :index => true, # Display array indices.
:sorted_hash_keys => false, :html => false, # Use ANSI color codes rather than HTML.
:sorted_hash_keys => false, # Do not sort hash keys.
:color => { :color => {
:array => :white, :array => :white,
:bigdecimal => :blue, :bigdecimal => :blue,
@ -104,7 +107,7 @@ class AwesomePrint
end end
end end
# Format a Struct. If @options[:indent] if negative left align hash keys. # Format a Struct. If @options[:indent] is negative left align hash keys.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
def awesome_struct(s) def awesome_struct(s)
h = {} h = {}
@ -242,10 +245,11 @@ class AwesomePrint
# Pick the color and apply it to the given string as necessary. # Pick the color and apply it to the given string as necessary.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
def colorize(s, type) def colorize(s, type)
if @options[:plain] || @options[:color][type].nil? || !colorize? s = CGI.escapeHTML(s) if @options[:html]
s if @options[:plain] || !@options[:color][type] || !colorize?
@options[:html] ? "<pre>#{s}</pre>" : s
else else
s.send(@options[:color][type]) s.send(@options[:color][type], @options[:html])
end end
end end
@ -326,6 +330,13 @@ class AwesomePrint
@@force_colors || (STDOUT.tty? && ((ENV['TERM'] && ENV['TERM'] != 'dumb') || ENV['ANSICON'])) @@force_colors || (STDOUT.tty? && ((ENV['TERM'] && ENV['TERM'] != 'dumb') || ENV['ANSICON']))
end end
# Class accessor to force colorized output (ex. forked subprocess where TERM
# might be dumb).
#------------------------------------------------------------------------------
def self.force_colors!(value = true)
@@force_colors = value
end
# Class accessors for custom defaults. # Class accessors for custom defaults.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
def self.defaults def self.defaults
@ -336,11 +347,4 @@ class AwesomePrint
@@defaults = args @@defaults = args
end end
# Class accessor to force colorized output (ex. forked subprocess where TERM
# might be dumb).
#------------------------------------------------------------------------------
def self.force_colors!(value = true)
@@force_colors = value
end
end end

View file

@ -5,30 +5,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
module AwesomePrintActionView module AwesomePrintActionView
def self.included(base) # Use HTML colors and add default "debug_dump" class to the resulting HTML.
unless base.const_defined?(:AP_ANSI_TO_HTML)
hash = {} # Build ANSI => HTML color map.
[ :gray, :red, :green, :yellow, :blue, :purple, :cyan, :white ].each_with_index do |color, i|
hash["\033[1;#{30+i}m"] = color
end
[ :black, :darkred, :darkgreen, :brown, :navy, :darkmagenta, :darkcyan, :slategray ].each_with_index do |color, i|
hash["\033[0;#{30+i}m"] = color
end
base.const_set(:AP_ANSI_TO_HTML, hash.freeze)
end
end
def ap_debug(object, options = {}) def ap_debug(object, options = {})
formatted = h(object.ai(options)) object.ai(options.merge(:html => true)).sub(/^<pre([\s>])/, '<pre class="debug_dump"\\1')
unless options[:plain]
self.class::AP_ANSI_TO_HTML.each do |key, value|
formatted.gsub!(key, %Q|<font color="#{value}">|)
end
formatted.gsub!("\033[0m", "</font>")
end
content_tag(:pre, formatted, :class => "debug_dump")
end end
alias_method :ap, :ap_debug alias_method :ap, :ap_debug

View file

@ -4,34 +4,19 @@ begin
require 'action_view' require 'action_view'
require 'ap/mixin/action_view' require 'ap/mixin/action_view'
describe "AwesomePrint ActionView extensions" do describe "AwesomePrint ActionView extension" do
before(:each) do before(:each) do
@view = ActionView::Base.new @view = ActionView::Base.new
end end
it "should wrap ap output with <pre> tag" do it "uses HTML and adds 'debug_dump' class to plain <pre> tag" do
obj = 42 markup = rand
@view.ap(obj, :plain => true).should == '<pre class="debug_dump">42</pre>' @view.ap(markup, :plain => true).should == %Q|<pre class="debug_dump">#{markup}</pre>|
end end
it "should encode HTML entities" do it "uses HTML and adds 'debug_dump' class to colorized <pre> tag" do
obj = " &<hello>" markup = ' &<hello>'
@view.ap(obj, :plain => true).should == '<pre class="debug_dump">&quot; &amp;&lt;hello&gt;&quot;</pre>' @view.ap(markup).should == '<pre class="debug_dump" style="color:brown">&quot; &amp;&lt;hello&gt;&quot;</pre>'
end
it "should convert primary ANSI colors to HTML" do
obj = 42
[ :gray, :red, :green, :yellow, :blue, :purple, :cyan, :white ].each do |color|
@view.ap(obj, :color => { :fixnum => color }).should == %Q|<pre class="debug_dump"><font color="#{color}">42</font></pre>|
end
end
it "should convert mixed ANSI colors to HTML" do
obj = 42
[ :grayish, :redish, :greenish, :yellowish, :blueish, :purpleish, :cyanish, :whiteish, :black, :pale ].zip(
[ :black, :darkred, :darkgreen, :brown, :navy, :darkmagenta, :darkcyan, :slategray, :black, :slategray ]) do |ansi, html|
@view.ap(obj, :color => { :fixnum => ansi }).should == %Q|<pre class="debug_dump"><font color="#{html}">42</font></pre>|
end
end end
end end

View file

@ -7,14 +7,6 @@ describe "AwesomePrint" do
stub_dotfile! stub_dotfile!
end end
describe "ap method" do
it "return value" do
object = rand
self.stub!(:puts)
(ap object).should eql(object)
end
end
describe "Array" do describe "Array" do
before(:each) do before(:each) do
@arr = [ 1, :two, "three", [ nil, [ true, false] ] ] @arr = [ 1, :two, "three", [ nil, [ true, false] ] ]
@ -469,6 +461,34 @@ EOS
grepped = hash.keys.grep(/^(\d+)\//) { $1 } grepped = hash.keys.grep(/^(\d+)\//) { $1 }
grepped.ai(:plain => true, :multiline => false).should == '[ "1", "2" ]' grepped.ai(:plain => true, :multiline => false).should == '[ "1", "2" ]'
end end
it "returns value passed as a parameter" do
object = rand
self.stub!(:puts)
(ap object).should == object
end
end
describe "HTML output" do
it "wraps ap output with plain <pre> tag" do
markup = rand
markup.ai(:html => true, :plain => true).should == "<pre>#{markup}</pre>"
end
it "wraps ap output with colorized <pre> tag" do
markup = rand
markup.ai(:html => true).should == %Q|<pre style="color:blue">#{markup}</pre>|
end
it "encodes HTML entities (plain)" do
markup = ' &<hello>'
markup.ai(:html => true, :plain => true).should == '<pre>&quot; &amp;&lt;hello&gt;&quot;</pre>'
end
it "encodes HTML entities (color)" do
markup = ' &<hello>'
markup.ai(:html => true).should == '<pre style="color:brown">&quot; &amp;&lt;hello&gt;&quot;</pre>'
end
end end
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------