From 2105efbf51f2cc3888d4eefceae5b93d038c000c Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 11:01:43 -0500 Subject: [PATCH 01/25] New approach for awesomeprint -- this uses a factory pattern to register formatters as they go. wip. --- .gitignore | 1 + .rspec | 1 + .travis.yml | 4 +- CHANGELOG.md | 2 + awesome_print.gemspec | 2 + lib/awesome_print.rb | 36 ++--- lib/awesome_print/colorize.rb | 2 + lib/awesome_print/ext/ostruct.rb | 27 ---- lib/awesome_print/formatter.rb | 131 ++++-------------- .../formatters/array_formatter.rb | 17 ++- .../formatters/base_formatter.rb | 65 ++------- .../formatters/bigdecimal_formatter.rb | 19 +++ .../formatters/class_formatter.rb | 11 +- lib/awesome_print/formatters/dir_formatter.rb | 10 +- .../formatters/fallback_formatter.rb | 51 +++++++ .../formatters/false_class_formatter.rb | 15 ++ .../formatters/file_formatter.rb | 10 +- .../formatters/hash_formatter.rb | 17 ++- .../formatters/integer_formatter.rb | 11 ++ .../formatters/method_formatter.rb | 11 +- .../formatters/nil_class_formatter.rb | 19 +++ .../formatters/object_formatter.rb | 14 +- lib/awesome_print/formatters/open_struct.rb | 19 +++ .../formatters/rational_formatter.rb | 11 ++ .../formatters/simple_formatter.rb | 14 +- .../formatters/string_formatter.rb | 11 ++ .../formatters/struct_formatter.rb | 14 +- .../formatters/symbol_formatter.rb | 18 +++ .../formatters/true_class_formatter.rb | 15 ++ lib/awesome_print/inspector.rb | 17 +-- lib/awesome_print/limiter.rb | 63 +++++++++ lib/awesome_print/registrar.rb | 20 +++ spec/ext/ostruct_spec.rb | 1 + spec/formats_spec.rb | 2 +- spec/spec_helper.rb | 2 + 35 files changed, 413 insertions(+), 270 deletions(-) delete mode 100644 lib/awesome_print/ext/ostruct.rb create mode 100644 lib/awesome_print/formatters/bigdecimal_formatter.rb create mode 100644 lib/awesome_print/formatters/fallback_formatter.rb create mode 100644 lib/awesome_print/formatters/false_class_formatter.rb create mode 100644 lib/awesome_print/formatters/integer_formatter.rb create mode 100644 lib/awesome_print/formatters/nil_class_formatter.rb create mode 100644 lib/awesome_print/formatters/open_struct.rb create mode 100644 lib/awesome_print/formatters/rational_formatter.rb create mode 100644 lib/awesome_print/formatters/string_formatter.rb create mode 100644 lib/awesome_print/formatters/symbol_formatter.rb create mode 100644 lib/awesome_print/formatters/true_class_formatter.rb create mode 100644 lib/awesome_print/limiter.rb create mode 100644 lib/awesome_print/registrar.rb diff --git a/.gitignore b/.gitignore index 9a3813e8..5ac8425b 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ Gemfile.lock # PROJECT::RBENV .ruby-gemset .awesome-print/ +.byebug_history diff --git a/.rspec b/.rspec index 4e1e0d2f..b7afd2de 100644 --- a/.rspec +++ b/.rspec @@ -1 +1,2 @@ +--format Fuubar --color diff --git a/.travis.yml b/.travis.yml index 5d9a377e..c662e7cd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,8 +24,8 @@ matrix: include: - rvm: ruby-head env: RUBYOPT="--enable-frozen-string-literal" - # allow_failures: - # - rvm: ruby-head + allow_failures: + - rvm: ruby-head addons: code_climate: diff --git a/CHANGELOG.md b/CHANGELOG.md index 597aff87..6a684620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,6 @@ ## master (unreleased) + +## 2.0.0 - Fixes spec suite to properly work via travis, gets a clean build [@imajes, others] - Adds support for ActiveModel::Errors [@dshinzie] - [#301] - removes use of `strip_heredoc` from specs as it's a rails dep [@kstephens] - [#303] diff --git a/awesome_print.gemspec b/awesome_print.gemspec index 25cce46b..735a7eac 100644 --- a/awesome_print.gemspec +++ b/awesome_print.gemspec @@ -24,7 +24,9 @@ Gem::Specification.new do |s| s.require_paths = ['lib'] s.add_development_dependency 'rspec', '>= 3.0.0' + s.add_development_dependency 'fuubar' s.add_development_dependency 'appraisal' + s.add_development_dependency 'byebug' s.add_development_dependency 'fakefs', '>= 0.2.1' s.add_development_dependency 'sqlite3' s.add_development_dependency 'nokogiri', '>= 1.6.5' diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index 06358a6b..eeaa7a41 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -15,27 +15,29 @@ require 'awesome_print/custom_defaults' require 'awesome_print/inspector' require 'awesome_print/formatter' + Dir["./lib/awesome_print/formatters/**/*.rb"].each { |f| require f } + require 'awesome_print/version' require 'awesome_print/core_ext/logger' if defined?(Logger) # # Load the following under normal circumstances as well as in Rails # console when required from ~/.irbrc or ~/.pryrc. # - require 'awesome_print/ext/active_record' if defined?(ActiveRecord) || AwesomePrint.rails_console? - require 'awesome_print/ext/active_support' if defined?(ActiveSupport) || AwesomePrint.rails_console? - # - # Load remaining extensions. - # - if defined?(ActiveSupport.on_load) - ActiveSupport.on_load(:action_view) do - require 'awesome_print/ext/action_view' - end - end - require 'awesome_print/ext/mongo_mapper' if defined?(MongoMapper) - require 'awesome_print/ext/mongoid' if defined?(Mongoid) - require 'awesome_print/ext/nokogiri' if defined?(Nokogiri) - require 'awesome_print/ext/nobrainer' if defined?(NoBrainer) - require 'awesome_print/ext/ripple' if defined?(Ripple) - require 'awesome_print/ext/sequel' if defined?(Sequel) - require 'awesome_print/ext/ostruct' if defined?(OpenStruct) + # require 'awesome_print/ext/active_record' if defined?(ActiveRecord) || AwesomePrint.rails_console? + # require 'awesome_print/ext/active_support' if defined?(ActiveSupport) || AwesomePrint.rails_console? + # # + # # Load remaining extensions. + # # + # if defined?(ActiveSupport.on_load) + # ActiveSupport.on_load(:action_view) do + # require 'awesome_print/ext/action_view' + # end + # end + # require 'awesome_print/ext/mongo_mapper' if defined?(MongoMapper) + # require 'awesome_print/ext/mongoid' if defined?(Mongoid) + # require 'awesome_print/ext/nokogiri' if defined?(Nokogiri) + # require 'awesome_print/ext/nobrainer' if defined?(NoBrainer) + # require 'awesome_print/ext/ripple' if defined?(Ripple) + # require 'awesome_print/ext/sequel' if defined?(Sequel) + # require 'awesome_print/ext/ostruct' if defined?(OpenStruct) end diff --git a/lib/awesome_print/colorize.rb b/lib/awesome_print/colorize.rb index f9adaf17..70e3335f 100644 --- a/lib/awesome_print/colorize.rb +++ b/lib/awesome_print/colorize.rb @@ -6,6 +6,8 @@ module Colorize # Pick the color and apply it to the given string as necessary. #------------------------------------------------------------------------------ def colorize(str, type) + puts "[COLORIZING] - using #{options[:color][type]} for #{type}" + str = CGI.escapeHTML(str) if options[:html] if options[:plain] || !options[:color][type] || !inspector.colorize? str diff --git a/lib/awesome_print/ext/ostruct.rb b/lib/awesome_print/ext/ostruct.rb deleted file mode 100644 index 0d89819a..00000000 --- a/lib/awesome_print/ext/ostruct.rb +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -module AwesomePrint - module OpenStruct - def self.included(base) - base.send :alias_method, :cast_without_ostruct, :cast - base.send :alias_method, :cast, :cast_with_ostruct - end - - def cast_with_ostruct(object, type) - cast = cast_without_ostruct(object, type) - if (defined?(::OpenStruct)) && (object.is_a?(::OpenStruct)) - cast = :open_struct_instance - end - cast - end - - def awesome_open_struct_instance(object) - "#{object.class} #{awesome_hash(object.marshal_dump)}" - end - end -end - -AwesomePrint::Formatter.send(:include, AwesomePrint::OpenStruct) diff --git a/lib/awesome_print/formatter.rb b/lib/awesome_print/formatter.rb index 50901387..49cae349 100644 --- a/lib/awesome_print/formatter.rb +++ b/lib/awesome_print/formatter.rb @@ -1,126 +1,53 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -require 'awesome_print/formatters' +require_relative 'colorize' module AwesomePrint class Formatter + include Colorize attr_reader :inspector, :options - CORE_FORMATTERS = [:array, :bigdecimal, :class, :dir, :file, :hash, :method, :rational, :set, :struct, :unboundmethod] - - def initialize(inspector) - @inspector = inspector - @options = inspector.options - end - - # Main entry point to format an object. - #------------------------------------------------------------------------------ - def format(object, type = nil) - core_class = cast(object, type) - awesome = if core_class != :self - send(:"awesome_#{core_class}", object) # Core formatters. - else - awesome_self(object, type) # Catch all that falls back to object.inspect. - end - awesome - end + # Acts as a class ivar + @registered_formatters = {} - # Hook this when adding custom formatters. Check out lib/awesome_print/ext - # directory for custom formatters that ship with awesome_print. - #------------------------------------------------------------------------------ - def cast(object, type) - CORE_FORMATTERS.include?(type) ? type : :self + # make it accessible + def self.registered_formatters + @registered_formatters end - private - - # Catch all method to format an arbitrary object. + # register a new formatter.. #------------------------------------------------------------------------------ - def awesome_self(object, type) - if @options[:raw] && object.instance_variables.any? - awesome_object(object) - elsif (hash = convert_to_hash(object)) - awesome_hash(hash) - else - awesome_simple(object.inspect.to_s, type, @inspector) - end - end - - def awesome_bigdecimal(n) - o = n.to_s('F') - type = :bigdecimal - awesome_simple(o, type, @inspector) - end - - def awesome_rational(n) - o = n.to_s - type = :rational - awesome_simple(o, type, @inspector) - end - - def awesome_simple(o, type, inspector = @inspector) - AwesomePrint::Formatters::SimpleFormatter.new(o, type, inspector).format - end - - def awesome_array(a) - Formatters::ArrayFormatter.new(a, @inspector).format - end - - def awesome_set(s) - Formatters::ArrayFormatter.new(s.to_a, @inspector).format - end - - def awesome_hash(h) - Formatters::HashFormatter.new(h, @inspector).format - end - - def awesome_object(o) - Formatters::ObjectFormatter.new(o, @inspector).format - end - - def awesome_struct(s) - Formatters::StructFormatter.new(s, @inspector).format - end - - def awesome_method(m) - Formatters::MethodFormatter.new(m, @inspector).format + def self.register(formatter) + @registered_formatters[formatter.formatted_object_type.to_sym] = formatter end - alias :awesome_unboundmethod :awesome_method - def awesome_class(c) - Formatters::ClassFormatter.new(c, @inspector).format - end - - def awesome_file(f) - Formatters::FileFormatter.new(f, @inspector).format + def initialize(inspector) + @inspector = inspector + @options = inspector.options end - def awesome_dir(d) - Formatters::DirFormatter.new(d, @inspector).format - end - # Utility methods. + # Main entry point to format an object. + # type is determined by Inspector#printable #------------------------------------------------------------------------------ - def convert_to_hash(object) - if !object.respond_to?(:to_hash) - return nil - end + def format(object, type = nil) + puts "[FORMAT] #{type.to_s.red} >>> #{object}" - if object.method(:to_hash).arity != 0 - return nil - end + format_with = active_formatter(type) + puts "[ACTIVE] using > #{format_with.to_s.blueish} < to format" - hash = object.to_hash - if !hash.respond_to?(:keys) || !hash.respond_to?('[]') - return nil + if format_with && format_with.send(:formattable?, object) + format_with.new(@inspector).format(object) + else + puts "[FALLBACK] well darn, we're just gonna have to fb" + # in this case, formatter is missing or fails format test + AwesomePrint::Formatters::FallbackFormatter.new(@inspector).format(object) end + end - return hash + def active_formatter(type) + self.class.registered_formatters[type] end end end + diff --git a/lib/awesome_print/formatters/array_formatter.rb b/lib/awesome_print/formatters/array_formatter.rb index 3340a77a..5381594e 100644 --- a/lib/awesome_print/formatters/array_formatter.rb +++ b/lib/awesome_print/formatters/array_formatter.rb @@ -3,16 +3,19 @@ module AwesomePrint module Formatters class ArrayFormatter < BaseFormatter - attr_reader :array, :inspector, :options - def initialize(array, inspector) - @array = array - @inspector = inspector - @options = inspector.options + formatter_for :array + + def self.formattable?(object) + object.is_a?(Array) end - def format - if array.length.zero? + attr_reader :array + + def format(object) + @array = object + + if object.length.zero? '[]' elsif methods_array? methods_array diff --git a/lib/awesome_print/formatters/base_formatter.rb b/lib/awesome_print/formatters/base_formatter.rb index c7f71c65..61897a11 100644 --- a/lib/awesome_print/formatters/base_formatter.rb +++ b/lib/awesome_print/formatters/base_formatter.rb @@ -1,68 +1,26 @@ require_relative '../colorize' +require_relative '../limiter' +require_relative '../registrar' module AwesomePrint module Formatters class BaseFormatter + include Colorize + include Registrar + include Limiter - DEFAULT_LIMIT_SIZE = 7 + attr_reader :object, :inspector, :options - # To support limited output, for example: - # - # ap ('a'..'z').to_a, :limit => 3 - # [ - # [ 0] "a", - # [ 1] .. [24], - # [25] "z" - # ] - # - # ap (1..100).to_a, :limit => true # Default limit is 7. - # [ - # [ 0] 1, - # [ 1] 2, - # [ 2] 3, - # [ 3] .. [96], - # [97] 98, - # [98] 99, - # [99] 100 - # ] - #------------------------------------------------------------------------------ - def should_be_limited? - options[:limit] or (options[:limit].is_a?(Integer) and options[:limit] > 0) + def initialize(inspector) + @inspector = inspector + @options = inspector.options end - def get_limit_size - case options[:limit] - when true - DEFAULT_LIMIT_SIZE - else - options[:limit] - end + def format(object) + raise NotImplementedError end - def limited(data, width, is_hash = false) - limit = get_limit_size - if data.length <= limit - data - else - # Calculate how many elements to be displayed above and below the separator. - head = limit / 2 - tail = head - (limit - 1) % 2 - - # Add the proper elements to the temp array and format the separator. - temp = data[0, head] + [nil] + data[-tail, tail] - - temp[head] = if is_hash - "#{indent}#{data[head].strip} .. #{data[data.length - tail - 1].strip}" - else - "#{indent}[#{head.to_s.rjust(width)}] .. [#{data.length - tail - 1}]" - end - - temp - end - end - - def method_tuple(method) if method.respond_to?(:parameters) # Ruby 1.9.2+ # See http://readruby.chengguangnan.com/methods#method-objects-parameters @@ -104,6 +62,7 @@ def method_tuple(method) # # Indentation related methods + # FIXME: move to Indentator?... #----------------------------------------- def indentation inspector.current_indentation diff --git a/lib/awesome_print/formatters/bigdecimal_formatter.rb b/lib/awesome_print/formatters/bigdecimal_formatter.rb new file mode 100644 index 00000000..a626b939 --- /dev/null +++ b/lib/awesome_print/formatters/bigdecimal_formatter.rb @@ -0,0 +1,19 @@ +require_relative 'base_formatter' + +module AwesomePrint + module Formatters + class BigdecimalFormatter < BaseFormatter + + formatter_for :bigdecimal + + def self.formattable?(object) + true + end + + def format(object) + colorize(object.to_s('F'), self.class.formatted_object_type) + end + + end + end +end diff --git a/lib/awesome_print/formatters/class_formatter.rb b/lib/awesome_print/formatters/class_formatter.rb index d5082ea3..417acedb 100644 --- a/lib/awesome_print/formatters/class_formatter.rb +++ b/lib/awesome_print/formatters/class_formatter.rb @@ -4,16 +4,15 @@ module AwesomePrint module Formatters class ClassFormatter < BaseFormatter - attr_reader :klass, :inspector, :options + formatter_for :class - def initialize(klass, inspector) - @klass = klass - @inspector = inspector - @options = inspector.options + def self.formattable?(object) + object.is_a?(Class) end - def format + def format(klass) superclass = klass.superclass + if superclass colorize("#{klass.inspect} < #{superclass}", :class) else diff --git a/lib/awesome_print/formatters/dir_formatter.rb b/lib/awesome_print/formatters/dir_formatter.rb index 0b1bc7bb..69bff1d1 100644 --- a/lib/awesome_print/formatters/dir_formatter.rb +++ b/lib/awesome_print/formatters/dir_formatter.rb @@ -5,15 +5,13 @@ module AwesomePrint module Formatters class DirFormatter < BaseFormatter - attr_reader :dir, :inspector, :options + formatter_for :dir - def initialize(dir, inspector) - @dir = dir - @inspector = inspector - @options = inspector.options + def self.formattable?(object) + object.is_a?(Dir) end - def format + def format(dir) ls = `ls -alF #{dir.path.shellescape}` colorize(ls.empty? ? dir.inspect : "#{dir.inspect}\n#{ls.chop}", :dir) end diff --git a/lib/awesome_print/formatters/fallback_formatter.rb b/lib/awesome_print/formatters/fallback_formatter.rb new file mode 100644 index 00000000..083e2982 --- /dev/null +++ b/lib/awesome_print/formatters/fallback_formatter.rb @@ -0,0 +1,51 @@ +require_relative 'base_formatter' + +# this handles some fallback logic to route things we don't know what they are + +module AwesomePrint + module Formatters + class FallbackFormatter < BaseFormatter + + formatter_for :self + + def self.formattable?(object) + true + end + + def format(object) + if @options[:raw] && object.instance_variables.any? + Formatters::ObjectFormatter.new(@inspector).format(object) + elsif (hash = convert_to_hash(object)) + Formatters::HashFormatter.new(@inspector).format(hash) + else + Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s) + end + end + + + private + + # Utility methods. + #------------------------------------------------------------------------------ + # FIXME: this could be super fixed. + # + def convert_to_hash(object) + if !object.respond_to?(:to_hash) + return nil + end + + if object.method(:to_hash).arity != 0 + return nil + end + + hash = object.to_hash + if !hash.respond_to?(:keys) || !hash.respond_to?('[]') + return nil + end + + return hash + end + + end + end +end diff --git a/lib/awesome_print/formatters/false_class_formatter.rb b/lib/awesome_print/formatters/false_class_formatter.rb new file mode 100644 index 00000000..f069cf4b --- /dev/null +++ b/lib/awesome_print/formatters/false_class_formatter.rb @@ -0,0 +1,15 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class FalseClassFormatter < SimpleFormatter + + formatter_for :falseclass + + def self.formattable?(object) + object == false + end + + end + end +end diff --git a/lib/awesome_print/formatters/file_formatter.rb b/lib/awesome_print/formatters/file_formatter.rb index 68c59da0..10d97e46 100644 --- a/lib/awesome_print/formatters/file_formatter.rb +++ b/lib/awesome_print/formatters/file_formatter.rb @@ -5,15 +5,13 @@ module AwesomePrint module Formatters class FileFormatter < BaseFormatter - attr_reader :file, :inspector, :options + formatter_for :file - def initialize(file, inspector) - @file = file - @inspector = inspector - @options = inspector.options + def self.formattable?(object) + object.is_a?(File) end - def format + def format(file) ls = File.directory?(file) ? `ls -adlF #{file.path.shellescape}` : `ls -alF #{file.path.shellescape}` colorize(ls.empty? ? file.inspect : "#{file.inspect}\n#{ls.chop}", :file) end diff --git a/lib/awesome_print/formatters/hash_formatter.rb b/lib/awesome_print/formatters/hash_formatter.rb index c29bb63e..9228cf09 100644 --- a/lib/awesome_print/formatters/hash_formatter.rb +++ b/lib/awesome_print/formatters/hash_formatter.rb @@ -3,15 +3,20 @@ module AwesomePrint module Formatters class HashFormatter < BaseFormatter - attr_reader :hash, :inspector, :options - def initialize(hash, inspector) - @hash = hash - @inspector = inspector - @options = inspector.options + attr_reader :hash + + formatter_for :hash + + def self.formattable?(object) + object.is_a?(Hash) end - def format + # INSTANCE METHODS BELOW + + def format(hash) + @hash = hash + if hash.empty? empty_hash elsif multiline_hash? diff --git a/lib/awesome_print/formatters/integer_formatter.rb b/lib/awesome_print/formatters/integer_formatter.rb new file mode 100644 index 00000000..b69cef1b --- /dev/null +++ b/lib/awesome_print/formatters/integer_formatter.rb @@ -0,0 +1,11 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class IntegerFormatter < SimpleFormatter + + formatter_for :integer + + end + end +end diff --git a/lib/awesome_print/formatters/method_formatter.rb b/lib/awesome_print/formatters/method_formatter.rb index 26c398db..a61312f4 100644 --- a/lib/awesome_print/formatters/method_formatter.rb +++ b/lib/awesome_print/formatters/method_formatter.rb @@ -4,15 +4,14 @@ module AwesomePrint module Formatters class MethodFormatter < BaseFormatter - attr_reader :method, :inspector, :options + formatter_for :method - def initialize(method, inspector) - @method = method - @inspector = inspector - @options = inspector.options + def self.formattable?(object) + puts "formattable? for METHOD..." + true end - def format + def format(method) name, args, owner = method_tuple(method) "#{colorize(owner, :class)}##{colorize(name, :method)}#{colorize(args, :args)}" diff --git a/lib/awesome_print/formatters/nil_class_formatter.rb b/lib/awesome_print/formatters/nil_class_formatter.rb new file mode 100644 index 00000000..5abf5cfc --- /dev/null +++ b/lib/awesome_print/formatters/nil_class_formatter.rb @@ -0,0 +1,19 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class NilClassFormatter < SimpleFormatter + + formatter_for :nilclass + + def self.formattable?(object) + object == nil + end + + def format(object) + colorize('nil', self.class.formatted_object_type) + end + + end + end +end diff --git a/lib/awesome_print/formatters/object_formatter.rb b/lib/awesome_print/formatters/object_formatter.rb index 49334f70..0b0b3441 100644 --- a/lib/awesome_print/formatters/object_formatter.rb +++ b/lib/awesome_print/formatters/object_formatter.rb @@ -4,16 +4,18 @@ module AwesomePrint module Formatters class ObjectFormatter < BaseFormatter - attr_reader :object, :variables, :inspector, :options + formatter_for :object - def initialize(object, inspector) + def self.formattable?(object) + object.is_a?(Object) + end + + attr_reader :variables + + def format(object) @object = object @variables = object.instance_variables - @inspector = inspector - @options = inspector.options - end - def format vars = variables.map do |var| property = var.to_s[1..-1].to_sym # to_s because of some monkey patching done by Puppet. accessor = if object.respond_to?(:"#{property}=") diff --git a/lib/awesome_print/formatters/open_struct.rb b/lib/awesome_print/formatters/open_struct.rb new file mode 100644 index 00000000..6d9674c8 --- /dev/null +++ b/lib/awesome_print/formatters/open_struct.rb @@ -0,0 +1,19 @@ +require_relative 'base_formatter' + +module AwesomePrint + module Formatters + class OpenStruct < BaseFormatter + + formatter_for :openstruct + + def self.formattable?(object) + defined?(::OpenStruct) && object.is_a?(::OpenStruct) + end + + def format(object) + "#{object.class} #{HashFormatter.new(inspector).format(object.marshal_dump)}" + end + + end + end +end diff --git a/lib/awesome_print/formatters/rational_formatter.rb b/lib/awesome_print/formatters/rational_formatter.rb new file mode 100644 index 00000000..c91e6328 --- /dev/null +++ b/lib/awesome_print/formatters/rational_formatter.rb @@ -0,0 +1,11 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class RationalFormatter < SimpleFormatter + + formatter_for :rational + + end + end +end diff --git a/lib/awesome_print/formatters/simple_formatter.rb b/lib/awesome_print/formatters/simple_formatter.rb index bdd274f2..04d403ec 100644 --- a/lib/awesome_print/formatters/simple_formatter.rb +++ b/lib/awesome_print/formatters/simple_formatter.rb @@ -4,18 +4,16 @@ module AwesomePrint module Formatters class SimpleFormatter < BaseFormatter - attr_reader :string, :type, :inspector, :options + formatter_for :simple - def initialize(string, type, inspector) - @string = string - @type = type - @inspector = inspector - @options = inspector.options + def self.formattable?(object) + object.respond_to?(:to_s) end - def format - colorize(string, type) + def format(object) + colorize(object.to_s, self.class.formatted_object_type) end + end end end diff --git a/lib/awesome_print/formatters/string_formatter.rb b/lib/awesome_print/formatters/string_formatter.rb new file mode 100644 index 00000000..7beaf626 --- /dev/null +++ b/lib/awesome_print/formatters/string_formatter.rb @@ -0,0 +1,11 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class StringFormatter < SimpleFormatter + + formatter_for :string + + end + end +end diff --git a/lib/awesome_print/formatters/struct_formatter.rb b/lib/awesome_print/formatters/struct_formatter.rb index 18bebaa9..66ecf4f2 100644 --- a/lib/awesome_print/formatters/struct_formatter.rb +++ b/lib/awesome_print/formatters/struct_formatter.rb @@ -4,16 +4,18 @@ module AwesomePrint module Formatters class StructFormatter < BaseFormatter - attr_reader :struct, :variables, :inspector, :options + formatter_for :struct - def initialize(struct, inspector) + def self.formattable?(object) + object.is_a?(Struct) + end + + attr_reader :struct, :variables + + def format(struct) @struct = struct @variables = struct.members - @inspector = inspector - @options = inspector.options - end - def format vars = variables.map do |var| property = var.to_s[1..-1].to_sym # to_s because of some monkey patching done by Puppet. accessor = if struct.respond_to?(:"#{property}=") diff --git a/lib/awesome_print/formatters/symbol_formatter.rb b/lib/awesome_print/formatters/symbol_formatter.rb new file mode 100644 index 00000000..c97561b6 --- /dev/null +++ b/lib/awesome_print/formatters/symbol_formatter.rb @@ -0,0 +1,18 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class SymbolFormatter < SimpleFormatter + + formatter_for :symbol + + def self.formattable?(object) + object.respond_to?(:to_s) + end + + def format(object) + colorize(object.to_s, self.class.formatted_object_type) + end + end + end +end diff --git a/lib/awesome_print/formatters/true_class_formatter.rb b/lib/awesome_print/formatters/true_class_formatter.rb new file mode 100644 index 00000000..de466972 --- /dev/null +++ b/lib/awesome_print/formatters/true_class_formatter.rb @@ -0,0 +1,15 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class TrueClassFormatter < SimpleFormatter + + formatter_for :trueclass + + def self.formattable?(object) + object == true + end + + end + end +end diff --git a/lib/awesome_print/inspector.rb b/lib/awesome_print/inspector.rb index 3c3fe110..a98b2d7f 100644 --- a/lib/awesome_print/inspector.rb +++ b/lib/awesome_print/inspector.rb @@ -42,6 +42,7 @@ def initialize(options = {}) rational: :blue, string: :yellowish, struct: :pale, + openstruct: :pale, symbol: :cyanish, time: :greenish, trueclass: :green, @@ -106,9 +107,10 @@ def colorize? #--------------------------------------------------------------------------- def nested(object) case printable(object) - when :array then @formatter.colorize('[...]', :array) - when :hash then @formatter.colorize('{...}', :hash) - when :struct then @formatter.colorize('{...}', :struct) + when :array then @formatter.colorize('[...]', :array) + when :hash then @formatter.colorize('{...}', :hash) + when :struct then @formatter.colorize('{...}', :struct) + when :openstruct then @formatter.colorize('{...}', :openstruct) else @formatter.colorize("...#{object.class}...", :class) end end @@ -123,14 +125,7 @@ def unnested(object) # base class. #--------------------------------------------------------------------------- def printable(object) - case object - when Array then :array - when Hash then :hash - when File then :file - when Dir then :dir - when Struct then :struct - else object.class.to_s.gsub(/:+/, '_').downcase.to_sym - end + object.class.to_s.gsub(/:+/, '_').downcase.to_sym end # Update @options by first merging the :color hash and then the remaining diff --git a/lib/awesome_print/limiter.rb b/lib/awesome_print/limiter.rb new file mode 100644 index 00000000..4c609b12 --- /dev/null +++ b/lib/awesome_print/limiter.rb @@ -0,0 +1,63 @@ +module AwesomePrint + module Limiter + + DEFAULT_LIMIT_SIZE = 7 + + # To support limited output, for example: + # + # ap ('a'..'z').to_a, :limit => 3 + # [ + # [ 0] "a", + # [ 1] .. [24], + # [25] "z" + # ] + # + # ap (1..100).to_a, :limit => true # Default limit is 7. + # [ + # [ 0] 1, + # [ 1] 2, + # [ 2] 3, + # [ 3] .. [96], + # [97] 98, + # [98] 99, + # [99] 100 + # ] + #------------------------------------------------------------------------------ + def should_be_limited? + options[:limit] or (options[:limit].is_a?(Integer) and options[:limit] > 0) + end + + def get_limit_size + case options[:limit] + when true + DEFAULT_LIMIT_SIZE + else + options[:limit] + end + end + + def limited(data, width, is_hash = false) + limit = get_limit_size + if data.length <= limit + data + else + # Calculate how many elements to be displayed above and below the separator. + head = limit / 2 + tail = head - (limit - 1) % 2 + + # Add the proper elements to the temp array and format the separator. + temp = data[0, head] + [nil] + data[-tail, tail] + + temp[head] = if is_hash + "#{indent}#{data[head].strip} .. #{data[data.length - tail - 1].strip}" + else + "#{indent}[#{head.to_s.rjust(width)}] .. [#{data.length - tail - 1}]" + end + + temp + end + end + + + end +end diff --git a/lib/awesome_print/registrar.rb b/lib/awesome_print/registrar.rb new file mode 100644 index 00000000..a63475e4 --- /dev/null +++ b/lib/awesome_print/registrar.rb @@ -0,0 +1,20 @@ +module AwesomePrint + module Registrar + + def self.included(base) + base.send(:extend, ClassMethods) + end + + module ClassMethods + + attr_accessor :formatted_object_type + + def formatter_for(type) + self.formatted_object_type = type + + AwesomePrint::Formatter.register(self) + end + end + + end +end diff --git a/spec/ext/ostruct_spec.rb b/spec/ext/ostruct_spec.rb index 55a4d338..27884ac0 100644 --- a/spec/ext/ostruct_spec.rb +++ b/spec/ext/ostruct_spec.rb @@ -1,4 +1,5 @@ require 'spec_helper' +require 'ostruct' RSpec.describe 'AwesomePrint Ostruct extension' do before do diff --git a/spec/formats_spec.rb b/spec/formats_spec.rb index 9427b442..2f755e91 100644 --- a/spec/formats_spec.rb +++ b/spec/formats_spec.rb @@ -119,7 +119,7 @@ EOS end - it 'colored single line' do + it 'colored single line', focus: true do expect(@arr.ai(multiline: false)).to eq("[ \e[1;34m1\e[0m, \e[0;36m:two\e[0m, \e[0;33m\"three\"\e[0m, [ \e[1;31mnil\e[0m, [ \e[1;32mtrue\e[0m, \e[1;31mfalse\e[0m ] ] ]") end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index d2ef52bd..a31568f0 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -25,6 +25,8 @@ require file end +require 'byebug' + ExtVerifier.require_dependencies!( %w( rails From 3738676ed6bc1bfe95ebfe001602efc249438949 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 11:55:44 -0500 Subject: [PATCH 02/25] splits spec, formalizes output for string/symbol --- .../formatters/string_formatter.rb | 3 + .../formatters/symbol_formatter.rb | 2 +- spec/formats_spec.rb | 779 ------------------ spec/formatters/array_spec.rb | 251 ++++++ spec/formatters/big_decimal_spec.rb | 28 + spec/formatters/class_spec.rb | 91 ++ spec/formatters/dir_file_spec.rb | 42 + spec/formatters/hash_spec.rb | 284 +++++++ spec/{ext => formatters}/ostruct_spec.rb | 0 spec/formatters/set_spec.rb | 49 ++ spec/formatters/struct_spec.rb | 61 ++ spec/merge_options_spec.rb | 13 + 12 files changed, 823 insertions(+), 780 deletions(-) delete mode 100644 spec/formats_spec.rb create mode 100644 spec/formatters/array_spec.rb create mode 100644 spec/formatters/big_decimal_spec.rb create mode 100644 spec/formatters/class_spec.rb create mode 100644 spec/formatters/dir_file_spec.rb create mode 100644 spec/formatters/hash_spec.rb rename spec/{ext => formatters}/ostruct_spec.rb (100%) create mode 100644 spec/formatters/set_spec.rb create mode 100644 spec/formatters/struct_spec.rb create mode 100644 spec/merge_options_spec.rb diff --git a/lib/awesome_print/formatters/string_formatter.rb b/lib/awesome_print/formatters/string_formatter.rb index 7beaf626..bc02e926 100644 --- a/lib/awesome_print/formatters/string_formatter.rb +++ b/lib/awesome_print/formatters/string_formatter.rb @@ -6,6 +6,9 @@ class StringFormatter < SimpleFormatter formatter_for :string + def format(object) + colorize("\"#{object.to_s}\"", self.class.formatted_object_type) + end end end end diff --git a/lib/awesome_print/formatters/symbol_formatter.rb b/lib/awesome_print/formatters/symbol_formatter.rb index c97561b6..8331bc6c 100644 --- a/lib/awesome_print/formatters/symbol_formatter.rb +++ b/lib/awesome_print/formatters/symbol_formatter.rb @@ -11,7 +11,7 @@ def self.formattable?(object) end def format(object) - colorize(object.to_s, self.class.formatted_object_type) + colorize(":#{object.to_s}", self.class.formatted_object_type) end end end diff --git a/spec/formats_spec.rb b/spec/formats_spec.rb deleted file mode 100644 index 2f755e91..00000000 --- a/spec/formats_spec.rb +++ /dev/null @@ -1,779 +0,0 @@ -require 'spec_helper' -require 'bigdecimal' -require 'rational' -require 'set' - -RSpec.describe 'AwesomePrint' do - describe 'Array' do - before do - @arr = [1, :two, 'three', [nil, [true, false]]] - end - - it 'empty array' do - expect([].ai).to eq('[]') - end - - it 'plain multiline' do - expect(@arr.ai(plain: true)).to eq <<-EOS.strip -[ - [0] 1, - [1] :two, - [2] "three", - [3] [ - [0] nil, - [1] [ - [0] true, - [1] false - ] - ] -] -EOS - end - - it 'plain multiline without index' do - expect(@arr.ai(plain: true, index: false)).to eq <<-EOS.strip -[ - 1, - :two, - "three", - [ - nil, - [ - true, - false - ] - ] -] -EOS - end - - it 'plain multiline indented' do - expect(@arr.ai(plain: true, indent: 2)).to eq <<-EOS.strip -[ - [0] 1, - [1] :two, - [2] "three", - [3] [ - [0] nil, - [1] [ - [0] true, - [1] false - ] - ] -] -EOS - end - - it 'plain multiline indented without index' do - expect(@arr.ai(plain: true, indent: 2, index: false)).to eq <<-EOS.strip -[ - 1, - :two, - "three", - [ - nil, - [ - true, - false - ] - ] -] -EOS - end - - it 'plain single line' do - expect(@arr.ai(plain: true, multiline: false)).to eq('[ 1, :two, "three", [ nil, [ true, false ] ] ]') - end - - it 'colored multiline (default)' do - expect(@arr.ai).to eq <<-EOS.strip -[ - \e[1;37m[0] \e[0m\e[1;34m1\e[0m, - \e[1;37m[1] \e[0m\e[0;36m:two\e[0m, - \e[1;37m[2] \e[0m\e[0;33m\"three\"\e[0m, - \e[1;37m[3] \e[0m[ - \e[1;37m[0] \e[0m\e[1;31mnil\e[0m, - \e[1;37m[1] \e[0m[ - \e[1;37m[0] \e[0m\e[1;32mtrue\e[0m, - \e[1;37m[1] \e[0m\e[1;31mfalse\e[0m - ] - ] -] -EOS - end - - it 'colored multiline indented' do - expect(@arr.ai(indent: 8)).to eq <<-EOS.strip -[ - \e[1;37m[0] \e[0m\e[1;34m1\e[0m, - \e[1;37m[1] \e[0m\e[0;36m:two\e[0m, - \e[1;37m[2] \e[0m\e[0;33m\"three\"\e[0m, - \e[1;37m[3] \e[0m[ - \e[1;37m[0] \e[0m\e[1;31mnil\e[0m, - \e[1;37m[1] \e[0m[ - \e[1;37m[0] \e[0m\e[1;32mtrue\e[0m, - \e[1;37m[1] \e[0m\e[1;31mfalse\e[0m - ] - ] -] -EOS - end - - it 'colored single line', focus: true do - expect(@arr.ai(multiline: false)).to eq("[ \e[1;34m1\e[0m, \e[0;36m:two\e[0m, \e[0;33m\"three\"\e[0m, [ \e[1;31mnil\e[0m, [ \e[1;32mtrue\e[0m, \e[1;31mfalse\e[0m ] ] ]") - end - end - - #------------------------------------------------------------------------------ - describe 'Nested Array' do - before do - @arr = [1, 2] - @arr << @arr - end - - it 'plain multiline' do - expect(@arr.ai(plain: true)).to eq <<-EOS.strip -[ - [0] 1, - [1] 2, - [2] [...] -] -EOS - end - - it 'plain multiline without index' do - expect(@arr.ai(plain: true, index: false)).to eq <<-EOS.strip -[ - 1, - 2, - [...] -] -EOS - end - - it 'plain single line' do - expect(@arr.ai(plain: true, multiline: false)).to eq('[ 1, 2, [...] ]') - end - end - - #------------------------------------------------------------------------------ - describe 'Limited Output Array' do - before(:each) do - @arr = (1..1000).to_a - end - - it 'plain limited output large' do - expect(@arr.ai(plain: true, limit: true)).to eq <<-EOS.strip -[ - [ 0] 1, - [ 1] 2, - [ 2] 3, - [ 3] .. [996], - [997] 998, - [998] 999, - [999] 1000 -] -EOS - end - - it 'plain limited output small' do - @arr = @arr[0..3] - expect(@arr.ai(plain: true, limit: true)).to eq <<-EOS.strip -[ - [0] 1, - [1] 2, - [2] 3, - [3] 4 -] -EOS - end - - it 'plain limited output with 10 lines' do - expect(@arr.ai(plain: true, limit: 10)).to eq <<-EOS.strip -[ - [ 0] 1, - [ 1] 2, - [ 2] 3, - [ 3] 4, - [ 4] 5, - [ 5] .. [995], - [996] 997, - [997] 998, - [998] 999, - [999] 1000 -] -EOS - end - - it 'plain limited output with 11 lines' do - expect(@arr.ai(plain: true, limit: 11)).to eq <<-EOS.strip -[ - [ 0] 1, - [ 1] 2, - [ 2] 3, - [ 3] 4, - [ 4] 5, - [ 5] .. [994], - [995] 996, - [996] 997, - [997] 998, - [998] 999, - [999] 1000 -] -EOS - end - end - - #------------------------------------------------------------------------------ - describe 'Limited Output Hash' do - before(:each) do - @hash = ('a'..'z').inject({}) { |h, v| h.merge({ v => v.to_sym }) } - end - - it 'plain limited output' do - expect(@hash.ai(sort_keys: true, plain: true, limit: true)).to eq <<-EOS.strip -{ - "a" => :a, - "b" => :b, - "c" => :c, - "d" => :d .. "w" => :w, - "x" => :x, - "y" => :y, - "z" => :z -} -EOS - end - end - - #------------------------------------------------------------------------------ - describe 'Hash' do - before do - @hash = { 1 => { sym: { 'str' => { [1, 2, 3] => { { k: :v } => Hash } } } } } - end - - it 'empty hash' do - expect({}.ai).to eq('{}') - end - - it 'plain multiline' do - expect(@hash.ai(plain: true)).to eq <<-EOS.strip -{ - 1 => { - :sym => { - "str" => { - [ 1, 2, 3 ] => { - { :k => :v } => Hash < Object - } - } - } - } -} -EOS - end - - it 'new hash syntax' do - expect(@hash.ai(plain: true, ruby19_syntax: true)).to eq <<-EOS.strip -{ - 1 => { - sym: { - "str" => { - [ 1, 2, 3 ] => { - { k: :v } => Hash < Object - } - } - } - } -} -EOS - end - - it 'plain multiline indented' do - expect(@hash.ai(plain: true, indent: 1)).to eq <<-EOS.strip -{ - 1 => { - :sym => { - "str" => { - [ 1, 2, 3 ] => { - { :k => :v } => Hash < Object - } - } - } - } -} -EOS - end - - it 'plain single line' do - expect(@hash.ai(plain: true, multiline: false)).to eq('{ 1 => { :sym => { "str" => { [ 1, 2, 3 ] => { { :k => :v } => Hash < Object } } } } }') - end - - it 'colored multiline (default)' do - expect(@hash.ai).to eq <<-EOS.strip -{ - 1\e[0;37m => \e[0m{ - :sym\e[0;37m => \e[0m{ - \"str\"\e[0;37m => \e[0m{ - [ 1, 2, 3 ]\e[0;37m => \e[0m{ - { :k => :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m - } - } - } - } -} -EOS - end - - it 'colored with new hash syntax' do - expect(@hash.ai(ruby19_syntax: true)).to eq <<-EOS.strip -{ - 1\e[0;37m => \e[0m{ - sym\e[0;37m: \e[0m{ - \"str\"\e[0;37m => \e[0m{ - [ 1, 2, 3 ]\e[0;37m => \e[0m{ - { k: :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m - } - } - } - } -} -EOS - end - - it 'colored multiline indented' do - expect(@hash.ai(indent: 2)).to eq <<-EOS.strip -{ - 1\e[0;37m => \e[0m{ - :sym\e[0;37m => \e[0m{ - \"str\"\e[0;37m => \e[0m{ - [ 1, 2, 3 ]\e[0;37m => \e[0m{ - { :k => :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m - } - } - } - } -} -EOS - end - - it 'colored single line' do - expect(@hash.ai(multiline: false)).to eq("{ 1\e[0;37m => \e[0m{ :sym\e[0;37m => \e[0m{ \"str\"\e[0;37m => \e[0m{ [ 1, 2, 3 ]\e[0;37m => \e[0m{ { :k => :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m } } } } }") - end - - end - - #------------------------------------------------------------------------------ - describe 'Nested Hash' do - before do - @hash = {} - @hash[:a] = @hash - end - - it 'plain multiline' do - expect(@hash.ai(plain: true)).to eq <<-EOS.strip -{ - :a => {...} -} -EOS - end - - it 'plain single line' do - expect(@hash.ai(plain: true, multiline: false)).to eq('{ :a => {...} }') - end - end - - #------------------------------------------------------------------------------ - describe 'Hash with several keys' do - before do - @hash = { 'b' => 'b', :a => 'a', :z => 'z', 'alpha' => 'alpha' } - end - - it 'plain multiline' do - out = @hash.ai(plain: true) - if RUBY_VERSION.to_f < 1.9 # Order of @hash keys is not guaranteed. - expect(out).to match(/^\{[^\}]+\}/m) - expect(out).to match(/ "b" => "b",?/) - expect(out).to match(/ :a => "a",?/) - expect(out).to match(/ :z => "z",?/) - expect(out).to match(/ "alpha" => "alpha",?$/) - else - expect(out).to eq <<-EOS.strip -{ - "b" => "b", - :a => "a", - :z => "z", - "alpha" => "alpha" -} -EOS - end - end - - it 'plain multiline with sorted keys' do - expect(@hash.ai(plain: true, sort_keys: true)).to eq <<-EOS.strip -{ - :a => "a", - "alpha" => "alpha", - "b" => "b", - :z => "z" -} -EOS - end - - end - - #------------------------------------------------------------------------------ - describe 'Negative options[:indent]' do - # - # With Ruby < 1.9 the order of hash keys is not defined so we can't - # reliably compare the output string. - # - it 'hash keys must be left aligned' do - hash = { [0, 0, 255] => :yellow, :red => 'rgb(255, 0, 0)', 'magenta' => 'rgb(255, 0, 255)' } - out = hash.ai(plain: true, indent: -4, sort_keys: true) - expect(out).to eq <<-EOS.strip -{ - [ 0, 0, 255 ] => :yellow, - "magenta" => "rgb(255, 0, 255)", - :red => "rgb(255, 0, 0)" -} -EOS - end - - it 'nested hash keys should be indented (array of hashes)' do - arr = [{ a: 1, bb: 22, ccc: 333 }, { 1 => :a, 22 => :bb, 333 => :ccc }] - out = arr.ai(plain: true, indent: -4, sort_keys: true) - expect(out).to eq <<-EOS.strip -[ - [0] { - :a => 1, - :bb => 22, - :ccc => 333 - }, - [1] { - 1 => :a, - 22 => :bb, - 333 => :ccc - } -] -EOS - end - - it 'nested hash keys should be indented (hash of hashes)' do - arr = { first: { a: 1, bb: 22, ccc: 333 }, second: { 1 => :a, 22 => :bb, 333 => :ccc } } - out = arr.ai(plain: true, indent: -4, sort_keys: true) - expect(out).to eq <<-EOS.strip -{ - :first => { - :a => 1, - :bb => 22, - :ccc => 333 - }, - :second => { - 1 => :a, - 22 => :bb, - 333 => :ccc - } -} -EOS - end - end - - #------------------------------------------------------------------------------ - describe 'Class' do - it 'should show superclass (plain)' do - expect(self.class.ai(plain: true)).to eq("#{self.class} < #{self.class.superclass}") - end - - it 'should show superclass (color)' do - expect(self.class.ai).to eq("#{self.class} < #{self.class.superclass}".yellow) - end - end - - #------------------------------------------------------------------------------ - describe 'File' do - it 'should display a file (plain)' do - File.open(__FILE__, 'r') do |f| - expect(f.ai(plain: true)).to eq("#{f.inspect}\n" << `ls -alF #{f.path}`.chop) - end - end - end - - #------------------------------------------------------------------------------ - describe 'Dir' do - it 'should display a direcory (plain)' do - Dir.open(File.dirname(__FILE__)) do |d| - expect(d.ai(plain: true)).to eq("#{d.inspect}\n" << `ls -alF #{d.path}`.chop) - end - end - end - - #------------------------------------------------------------------------------ - describe 'BigDecimal and Rational' do - it 'should present BigDecimal object with arbitrary precision' do - big = BigDecimal('201020102010201020102010201020102010.4') - expect(big.ai(plain: true)).to eq('201020102010201020102010201020102010.4') - end - - it 'should present Rational object with arbitrary precision' do - rat = Rational(201020102010201020102010201020102010, 2) - out = rat.ai(plain: true) - # - # Ruby 1.9 slightly changed the format of Rational#to_s, see - # http://techtime.getharvest.com/blog/harvest-is-now-on-ruby-1-dot-9-3 and - # http://www.ruby-forum.com/topic/189397 - # - if RUBY_VERSION < '1.9' - expect(out).to eq('100510051005100510051005100510051005') - else - expect(out).to eq('100510051005100510051005100510051005/1') - end - end - end - - #------------------------------------------------------------------------------ - describe 'Utility methods' do - it 'should merge options' do - ap = AwesomePrint::Inspector.new - ap.send(:merge_options!, { color: { array: :black }, indent: 0 }) - options = ap.instance_variable_get('@options') - expect(options[:color][:array]).to eq(:black) - expect(options[:indent]).to eq(0) - end - end - - #------------------------------------------------------------------------------ - describe 'Set' do - before do - @arr = [1, :two, 'three'] - @set = Set.new(@arr) - end - - it 'empty set' do - expect(Set.new.ai).to eq([].ai) - end - - if RUBY_VERSION > '1.9' - it 'plain multiline' do - expect(@set.ai(plain: true)).to eq(@arr.ai(plain: true)) - end - - it 'plain multiline indented' do - expect(@set.ai(plain: true, indent: 1)).to eq(@arr.ai(plain: true, indent: 1)) - end - - it 'plain single line' do - expect(@set.ai(plain: true, multiline: false)).to eq(@arr.ai(plain: true, multiline: false)) - end - - it 'colored multiline (default)' do - expect(@set.ai).to eq(@arr.ai) - end - else # Prior to Ruby 1.9 the order of set values is unpredicatble. - it 'plain multiline' do - expect(@set.sort_by { |x| x.to_s }.ai(plain: true)).to eq(@arr.sort_by { |x| x.to_s }.ai(plain: true)) - end - - it 'plain multiline indented' do - expect(@set.sort_by { |x| x.to_s }.ai(plain: true, indent: 1)).to eq(@arr.sort_by { |x| x.to_s }.ai(plain: true, indent: 1)) - end - - it 'plain single line' do - expect(@set.sort_by { |x| x.to_s }.ai(plain: true, multiline: false)).to eq(@arr.sort_by { |x| x.to_s }.ai(plain: true, multiline: false)) - end - - it 'colored multiline (default)' do - expect(@set.sort_by { |x| x.to_s }.ai).to eq(@arr.sort_by { |x| x.to_s }.ai) - end - end - end - - #------------------------------------------------------------------------------ - describe 'Struct' do - before do - @struct = unless defined?(Struct::SimpleStruct) - Struct.new('SimpleStruct', :name, :address).new - else - Struct::SimpleStruct.new - end - @struct.name = 'Herman Munster' - @struct.address = '1313 Mockingbird Lane' - end - - it 'empty struct' do - expect(Struct.new('EmptyStruct').ai).to eq("\e[1;33mStruct::EmptyStruct < Struct\e[0m") - end - - it 'plain multiline' do - s1 = <<-EOS.strip - address = \"1313 Mockingbird Lane\", - name = \"Herman Munster\" -EOS - s2 = <<-EOS.strip - name = \"Herman Munster\", - address = \"1313 Mockingbird Lane\" -EOS - expect(@struct.ai(plain: true)).to satisfy { |out| out.match(s1) || out.match(s2) } - end - - it 'plain multiline indented' do - s1 = <<-EOS.strip - address = "1313 Mockingbird Lane", - name = "Herman Munster" -EOS - s2 = <<-EOS.strip - name = "Herman Munster", - address = "1313 Mockingbird Lane" -EOS - expect(@struct.ai(plain: true, indent: 1)).to satisfy { |out| out.match(s1) || out.match(s2) } - end - - it 'plain single line' do - s1 = 'address = "1313 Mockingbird Lane", name = "Herman Munster"' - s2 = 'name = "Herman Munster", address = "1313 Mockingbird Lane"' - expect(@struct.ai(plain: true, multiline: false)).to satisfy { |out| out.match(s1) || out.match(s2) } - end - - it 'colored multiline (default)' do - s1 = <<-EOS.strip - address\e[0;37m = \e[0m\e[0;33m\"1313 Mockingbird Lane\"\e[0m, - name\e[0;37m = \e[0m\e[0;33m\"Herman Munster\"\e[0m -EOS - s2 = <<-EOS.strip - name\e[0;37m = \e[0m\e[0;33m\"Herman Munster\"\e[0m, - address\e[0;37m = \e[0m\e[0;33m\"1313 Mockingbird Lane\"\e[0m -EOS - expect(@struct.ai).to satisfy { |out| out.include?(s1) || out.include?(s2) } - end - end - - #------------------------------------------------------------------------------ - describe 'Inherited from standard Ruby classes' do - after do - Object.instance_eval { remove_const :My } if defined?(My) - end - - it 'inherited from Array should be displayed as Array' do - class My < Array; end - - my = My.new([1, :two, 'three', [nil, [true, false]]]) - expect(my.ai(plain: true)).to eq <<-EOS.strip -[ - [0] 1, - [1] :two, - [2] "three", - [3] [ - [0] nil, - [1] [ - [0] true, - [1] false - ] - ] -] -EOS - end - - it 'inherited from Hash should be displayed as Hash' do - class My < Hash; end - - my = My[{ 1 => { sym: { 'str' => { [1, 2, 3] => { { k: :v } => Hash } } } } }] - expect(my.ai(plain: true)).to eq <<-EOS.strip -{ - 1 => { - :sym => { - "str" => { - [ 1, 2, 3 ] => { - { :k => :v } => Hash < Object - } - } - } - } -} -EOS - end - - it 'inherited from File should be displayed as File' do - class My < File; end - - my = File.new('/dev/null') rescue File.new('nul') - expect(my.ai(plain: true)).to eq("#{my.inspect}\n" << `ls -alF #{my.path}`.chop) - end - - it 'inherited from Dir should be displayed as Dir' do - class My < Dir; end - - require 'tmpdir' - my = My.new(Dir.tmpdir) - expect(my.ai(plain: true)).to eq("#{my.inspect}\n" << `ls -alF #{my.path}`.chop) - end - - it 'should handle a class that defines its own #send method' do - class My - def send(arg1, arg2, arg3); end - end - - my = My.new - expect { my.methods.ai(plain: true) }.not_to raise_error - end - - it 'should handle a class defines its own #method method (ex. request.method)' do - class My - def method - 'POST' - end - end - - my = My.new - expect { my.methods.ai(plain: true) }.not_to raise_error - end - - describe 'should handle a class that defines its own #to_hash method' do - it 'that takes arguments' do - class My - def to_hash(a, b) - end - end - - my = My.new - expect { my.ai(plain: true) }.not_to raise_error - end - - it 'that returns nil' do - class My - def to_hash() - return nil - end - end - - my = My.new - expect { my.ai(plain: true) }.not_to raise_error - end - - it "that returns an object that doesn't support #keys" do - class My - def to_hash() - object = Object.new - object.define_singleton_method('[]') { return nil } - - return object - end - end - - my = My.new - expect { my.ai(plain: true) }.not_to raise_error - end - - it "that returns an object that doesn't support subscripting" do - class My - def to_hash() - object = Object.new - object.define_singleton_method(:keys) { return [:foo] } - - return object - end - end - - my = My.new - expect { my.ai(plain: true) }.not_to raise_error - end - end - end -end diff --git a/spec/formatters/array_spec.rb b/spec/formatters/array_spec.rb new file mode 100644 index 00000000..a5fca744 --- /dev/null +++ b/spec/formatters/array_spec.rb @@ -0,0 +1,251 @@ +require_relative '../spec_helper' + +RSpec.describe 'AwesomePrint' do + describe 'Array' do + before do + @arr = [1, :two, 'three', [nil, [true, false]]] + end + + it 'empty array' do + expect([].ai).to eq('[]') + end + + it 'plain multiline' do + expect(@arr.ai(plain: true)).to eq <<-EOS.strip +[ + [0] 1, + [1] :two, + [2] "three", + [3] [ + [0] nil, + [1] [ + [0] true, + [1] false + ] + ] +] +EOS + end + + it 'plain multiline without index' do + expect(@arr.ai(plain: true, index: false)).to eq <<-EOS.strip +[ + 1, + :two, + "three", + [ + nil, + [ + true, + false + ] + ] +] +EOS + end + + it 'plain multiline indented' do + expect(@arr.ai(plain: true, indent: 2)).to eq <<-EOS.strip +[ + [0] 1, + [1] :two, + [2] "three", + [3] [ + [0] nil, + [1] [ + [0] true, + [1] false + ] + ] +] +EOS + end + + it 'plain multiline indented without index' do + expect(@arr.ai(plain: true, indent: 2, index: false)).to eq <<-EOS.strip +[ + 1, + :two, + "three", + [ + nil, + [ + true, + false + ] + ] +] +EOS + end + + it 'plain single line' do + expect(@arr.ai(plain: true, multiline: false)).to eq('[ 1, :two, "three", [ nil, [ true, false ] ] ]') + end + + it 'colored multiline (default)' do + expect(@arr.ai).to eq <<-EOS.strip +[ + \e[1;37m[0] \e[0m\e[1;34m1\e[0m, + \e[1;37m[1] \e[0m\e[0;36m:two\e[0m, + \e[1;37m[2] \e[0m\e[0;33m\"three\"\e[0m, + \e[1;37m[3] \e[0m[ + \e[1;37m[0] \e[0m\e[1;31mnil\e[0m, + \e[1;37m[1] \e[0m[ + \e[1;37m[0] \e[0m\e[1;32mtrue\e[0m, + \e[1;37m[1] \e[0m\e[1;31mfalse\e[0m + ] + ] +] +EOS + end + + it 'colored multiline indented' do + expect(@arr.ai(indent: 8)).to eq <<-EOS.strip +[ + \e[1;37m[0] \e[0m\e[1;34m1\e[0m, + \e[1;37m[1] \e[0m\e[0;36m:two\e[0m, + \e[1;37m[2] \e[0m\e[0;33m\"three\"\e[0m, + \e[1;37m[3] \e[0m[ + \e[1;37m[0] \e[0m\e[1;31mnil\e[0m, + \e[1;37m[1] \e[0m[ + \e[1;37m[0] \e[0m\e[1;32mtrue\e[0m, + \e[1;37m[1] \e[0m\e[1;31mfalse\e[0m + ] + ] +] +EOS + end + + it 'colored single line' do + expect(@arr.ai(multiline: false)).to eq("[ \e[1;34m1\e[0m, \e[0;36m:two\e[0m, \e[0;33m\"three\"\e[0m, [ \e[1;31mnil\e[0m, [ \e[1;32mtrue\e[0m, \e[1;31mfalse\e[0m ] ] ]") + end + end + + #------------------------------------------------------------------------------ + describe 'Nested Array' do + before do + @arr = [1, 2] + @arr << @arr + end + + it 'plain multiline' do + expect(@arr.ai(plain: true)).to eq <<-EOS.strip +[ + [0] 1, + [1] 2, + [2] [...] +] +EOS + end + + it 'plain multiline without index' do + expect(@arr.ai(plain: true, index: false)).to eq <<-EOS.strip +[ + 1, + 2, + [...] +] +EOS + end + + it 'plain single line' do + expect(@arr.ai(plain: true, multiline: false)).to eq('[ 1, 2, [...] ]') + end + end + + #------------------------------------------------------------------------------ + describe 'Limited Output Array' do + before(:each) do + @arr = (1..1000).to_a + end + + it 'plain limited output large' do + expect(@arr.ai(plain: true, limit: true)).to eq <<-EOS.strip +[ + [ 0] 1, + [ 1] 2, + [ 2] 3, + [ 3] .. [996], + [997] 998, + [998] 999, + [999] 1000 +] +EOS + end + + it 'plain limited output small' do + @arr = @arr[0..3] + expect(@arr.ai(plain: true, limit: true)).to eq <<-EOS.strip +[ + [0] 1, + [1] 2, + [2] 3, + [3] 4 +] +EOS + end + + it 'plain limited output with 10 lines' do + expect(@arr.ai(plain: true, limit: 10)).to eq <<-EOS.strip +[ + [ 0] 1, + [ 1] 2, + [ 2] 3, + [ 3] 4, + [ 4] 5, + [ 5] .. [995], + [996] 997, + [997] 998, + [998] 999, + [999] 1000 +] +EOS + end + + it 'plain limited output with 11 lines' do + expect(@arr.ai(plain: true, limit: 11)).to eq <<-EOS.strip +[ + [ 0] 1, + [ 1] 2, + [ 2] 3, + [ 3] 4, + [ 4] 5, + [ 5] .. [994], + [995] 996, + [996] 997, + [997] 998, + [998] 999, + [999] 1000 +] +EOS + end + end + + #------------------------------------------------------------------------------ + describe 'Inherited from standard Ruby classes' do + after do + Object.instance_eval { remove_const :My } if defined?(My) + end + + it 'inherited from Array should be displayed as Array' do + class My < Array; end + + my = My.new([1, :two, 'three', [nil, [true, false]]]) + expect(my.ai(plain: true)).to eq <<-EOS.strip +[ + [0] 1, + [1] :two, + [2] "three", + [3] [ + [0] nil, + [1] [ + [0] true, + [1] false + ] + ] +] +EOS + end + + end +end diff --git a/spec/formatters/big_decimal_spec.rb b/spec/formatters/big_decimal_spec.rb new file mode 100644 index 00000000..ce80d81a --- /dev/null +++ b/spec/formatters/big_decimal_spec.rb @@ -0,0 +1,28 @@ +require_relative '../spec_helper' +require 'bigdecimal' +require 'rational' + +RSpec.describe 'AwesomePrint' do + #------------------------------------------------------------------------------ + describe 'BigDecimal and Rational' do + it 'should present BigDecimal object with arbitrary precision' do + big = BigDecimal('201020102010201020102010201020102010.4') + expect(big.ai(plain: true)).to eq('201020102010201020102010201020102010.4') + end + + it 'should present Rational object with arbitrary precision' do + rat = Rational(201020102010201020102010201020102010, 2) + out = rat.ai(plain: true) + # + # Ruby 1.9 slightly changed the format of Rational#to_s, see + # http://techtime.getharvest.com/blog/harvest-is-now-on-ruby-1-dot-9-3 and + # http://www.ruby-forum.com/topic/189397 + # + if RUBY_VERSION < '1.9' + expect(out).to eq('100510051005100510051005100510051005') + else + expect(out).to eq('100510051005100510051005100510051005/1') + end + end + end +end diff --git a/spec/formatters/class_spec.rb b/spec/formatters/class_spec.rb new file mode 100644 index 00000000..c4267eff --- /dev/null +++ b/spec/formatters/class_spec.rb @@ -0,0 +1,91 @@ +require_relative '../spec_helper' + +RSpec.describe 'AwesomePrint' do + + describe 'Class' do + it 'should show superclass (plain)' do + expect(self.class.ai(plain: true)).to eq("#{self.class} < #{self.class.superclass}") + end + + it 'should show superclass (color)' do + expect(self.class.ai).to eq("#{self.class} < #{self.class.superclass}".yellow) + end + end + + describe 'Inherited from standard Ruby classes' do + after do + Object.instance_eval { remove_const :My } if defined?(My) + end + + it 'should handle a class that defines its own #send method' do + class My + def send(arg1, arg2, arg3); end + end + + my = My.new + expect { my.methods.ai(plain: true) }.not_to raise_error + end + + it 'should handle a class defines its own #method method (ex. request.method)' do + class My + def method + 'POST' + end + end + + my = My.new + expect { my.methods.ai(plain: true) }.not_to raise_error + end + + describe 'should handle a class that defines its own #to_hash method' do + it 'that takes arguments' do + class My + def to_hash(a, b) + end + end + + my = My.new + expect { my.ai(plain: true) }.not_to raise_error + end + + it 'that returns nil' do + class My + def to_hash() + return nil + end + end + + my = My.new + expect { my.ai(plain: true) }.not_to raise_error + end + + it "that returns an object that doesn't support #keys" do + class My + def to_hash() + object = Object.new + object.define_singleton_method('[]') { return nil } + + return object + end + end + + my = My.new + expect { my.ai(plain: true) }.not_to raise_error + end + + it "that returns an object that doesn't support subscripting" do + class My + def to_hash() + object = Object.new + object.define_singleton_method(:keys) { return [:foo] } + + return object + end + end + + my = My.new + expect { my.ai(plain: true) }.not_to raise_error + end + end + end +end diff --git a/spec/formatters/dir_file_spec.rb b/spec/formatters/dir_file_spec.rb new file mode 100644 index 00000000..e87d9159 --- /dev/null +++ b/spec/formatters/dir_file_spec.rb @@ -0,0 +1,42 @@ +require_relative '../spec_helper' + +RSpec.describe 'AwesomePrint' do + + describe 'File' do + it 'should display a file (plain)' do + File.open(__FILE__, 'r') do |f| + expect(f.ai(plain: true)).to eq("#{f.inspect}\n" << `ls -alF #{f.path}`.chop) + end + end + end + + describe 'Dir' do + it 'should display a direcory (plain)' do + Dir.open(File.dirname(__FILE__)) do |d| + expect(d.ai(plain: true)).to eq("#{d.inspect}\n" << `ls -alF #{d.path}`.chop) + end + end + end + + describe 'Inherited from standard Ruby classes' do + after do + Object.instance_eval { remove_const :My } if defined?(My) + end + + it 'inherited from File should be displayed as File' do + class My < File; end + + my = File.new('/dev/null') rescue File.new('nul') + expect(my.ai(plain: true)).to eq("#{my.inspect}\n" << `ls -alF #{my.path}`.chop) + end + + it 'inherited from Dir should be displayed as Dir' do + class My < Dir; end + + require 'tmpdir' + my = My.new(Dir.tmpdir) + expect(my.ai(plain: true)).to eq("#{my.inspect}\n" << `ls -alF #{my.path}`.chop) + end + + end +end diff --git a/spec/formatters/hash_spec.rb b/spec/formatters/hash_spec.rb new file mode 100644 index 00000000..104b750e --- /dev/null +++ b/spec/formatters/hash_spec.rb @@ -0,0 +1,284 @@ +require_relative '../spec_helper' + +RSpec.describe 'AwesomePrint' do + + #------------------------------------------------------------------------------ + describe 'Limited Output Hash' do + before(:each) do + @hash = ('a'..'z').inject({}) { |h, v| h.merge({ v => v.to_sym }) } + end + + it 'plain limited output' do + expect(@hash.ai(sort_keys: true, plain: true, limit: true)).to eq <<-EOS.strip +{ + "a" => :a, + "b" => :b, + "c" => :c, + "d" => :d .. "w" => :w, + "x" => :x, + "y" => :y, + "z" => :z +} +EOS + end + end + + #------------------------------------------------------------------------------ + describe 'Hash' do + before do + @hash = { 1 => { sym: { 'str' => { [1, 2, 3] => { { k: :v } => Hash } } } } } + end + + it 'empty hash' do + expect({}.ai).to eq('{}') + end + + it 'plain multiline' do + expect(@hash.ai(plain: true)).to eq <<-EOS.strip +{ + 1 => { + :sym => { + "str" => { + [ 1, 2, 3 ] => { + { :k => :v } => Hash < Object + } + } + } + } +} +EOS + end + + it 'new hash syntax' do + expect(@hash.ai(plain: true, ruby19_syntax: true)).to eq <<-EOS.strip +{ + 1 => { + sym: { + "str" => { + [ 1, 2, 3 ] => { + { k: :v } => Hash < Object + } + } + } + } +} +EOS + end + + it 'plain multiline indented' do + expect(@hash.ai(plain: true, indent: 1)).to eq <<-EOS.strip +{ + 1 => { + :sym => { + "str" => { + [ 1, 2, 3 ] => { + { :k => :v } => Hash < Object + } + } + } + } +} +EOS + end + + it 'plain single line' do + expect(@hash.ai(plain: true, multiline: false)).to eq('{ 1 => { :sym => { "str" => { [ 1, 2, 3 ] => { { :k => :v } => Hash < Object } } } } }') + end + + it 'colored multiline (default)' do + expect(@hash.ai).to eq <<-EOS.strip +{ + 1\e[0;37m => \e[0m{ + :sym\e[0;37m => \e[0m{ + \"str\"\e[0;37m => \e[0m{ + [ 1, 2, 3 ]\e[0;37m => \e[0m{ + { :k => :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m + } + } + } + } +} +EOS + end + + it 'colored with new hash syntax' do + expect(@hash.ai(ruby19_syntax: true)).to eq <<-EOS.strip +{ + 1\e[0;37m => \e[0m{ + sym\e[0;37m: \e[0m{ + \"str\"\e[0;37m => \e[0m{ + [ 1, 2, 3 ]\e[0;37m => \e[0m{ + { k: :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m + } + } + } + } +} +EOS + end + + it 'colored multiline indented' do + expect(@hash.ai(indent: 2)).to eq <<-EOS.strip +{ + 1\e[0;37m => \e[0m{ + :sym\e[0;37m => \e[0m{ + \"str\"\e[0;37m => \e[0m{ + [ 1, 2, 3 ]\e[0;37m => \e[0m{ + { :k => :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m + } + } + } + } +} +EOS + end + + it 'colored single line' do + expect(@hash.ai(multiline: false)).to eq("{ 1\e[0;37m => \e[0m{ :sym\e[0;37m => \e[0m{ \"str\"\e[0;37m => \e[0m{ [ 1, 2, 3 ]\e[0;37m => \e[0m{ { :k => :v }\e[0;37m => \e[0m\e[1;33mHash < Object\e[0m } } } } }") + end + + end + + #------------------------------------------------------------------------------ + describe 'Nested Hash' do + before do + @hash = {} + @hash[:a] = @hash + end + + it 'plain multiline' do + expect(@hash.ai(plain: true)).to eq <<-EOS.strip +{ + :a => {...} +} +EOS + end + + it 'plain single line' do + expect(@hash.ai(plain: true, multiline: false)).to eq('{ :a => {...} }') + end + end + + #------------------------------------------------------------------------------ + describe 'Hash with several keys' do + before do + @hash = { 'b' => 'b', :a => 'a', :z => 'z', 'alpha' => 'alpha' } + end + + it 'plain multiline' do + out = @hash.ai(plain: true) + if RUBY_VERSION.to_f < 1.9 # Order of @hash keys is not guaranteed. + expect(out).to match(/^\{[^\}]+\}/m) + expect(out).to match(/ "b" => "b",?/) + expect(out).to match(/ :a => "a",?/) + expect(out).to match(/ :z => "z",?/) + expect(out).to match(/ "alpha" => "alpha",?$/) + else + expect(out).to eq <<-EOS.strip +{ + "b" => "b", + :a => "a", + :z => "z", + "alpha" => "alpha" +} +EOS + end + end + + it 'plain multiline with sorted keys' do + expect(@hash.ai(plain: true, sort_keys: true)).to eq <<-EOS.strip +{ + :a => "a", + "alpha" => "alpha", + "b" => "b", + :z => "z" +} +EOS + end + + end + + #------------------------------------------------------------------------------ + describe 'Negative options[:indent]' do + # + # With Ruby < 1.9 the order of hash keys is not defined so we can't + # reliably compare the output string. + # + it 'hash keys must be left aligned' do + hash = { [0, 0, 255] => :yellow, :red => 'rgb(255, 0, 0)', 'magenta' => 'rgb(255, 0, 255)' } + out = hash.ai(plain: true, indent: -4, sort_keys: true) + expect(out).to eq <<-EOS.strip +{ + [ 0, 0, 255 ] => :yellow, + "magenta" => "rgb(255, 0, 255)", + :red => "rgb(255, 0, 0)" +} +EOS + end + + it 'nested hash keys should be indented (array of hashes)' do + arr = [{ a: 1, bb: 22, ccc: 333 }, { 1 => :a, 22 => :bb, 333 => :ccc }] + out = arr.ai(plain: true, indent: -4, sort_keys: true) + expect(out).to eq <<-EOS.strip +[ + [0] { + :a => 1, + :bb => 22, + :ccc => 333 + }, + [1] { + 1 => :a, + 22 => :bb, + 333 => :ccc + } +] +EOS + end + + it 'nested hash keys should be indented (hash of hashes)' do + arr = { first: { a: 1, bb: 22, ccc: 333 }, second: { 1 => :a, 22 => :bb, 333 => :ccc } } + out = arr.ai(plain: true, indent: -4, sort_keys: true) + expect(out).to eq <<-EOS.strip +{ + :first => { + :a => 1, + :bb => 22, + :ccc => 333 + }, + :second => { + 1 => :a, + 22 => :bb, + 333 => :ccc + } +} +EOS + end + end + + #------------------------------------------------------------------------------ + describe 'Inherited from standard Ruby classes' do + after do + Object.instance_eval { remove_const :My } if defined?(My) + end + + it 'inherited from Hash should be displayed as Hash' do + class My < Hash; end + + my = My[{ 1 => { sym: { 'str' => { [1, 2, 3] => { { k: :v } => Hash } } } } }] + expect(my.ai(plain: true)).to eq <<-EOS.strip +{ + 1 => { + :sym => { + "str" => { + [ 1, 2, 3 ] => { + { :k => :v } => Hash < Object + } + } + } + } +} +EOS + end + + end +end diff --git a/spec/ext/ostruct_spec.rb b/spec/formatters/ostruct_spec.rb similarity index 100% rename from spec/ext/ostruct_spec.rb rename to spec/formatters/ostruct_spec.rb diff --git a/spec/formatters/set_spec.rb b/spec/formatters/set_spec.rb new file mode 100644 index 00000000..73332d66 --- /dev/null +++ b/spec/formatters/set_spec.rb @@ -0,0 +1,49 @@ +require_relative '../spec_helper' +require 'set' + +RSpec.describe 'AwesomePrint' do + describe 'Set' do + before do + @arr = [1, :two, 'three'] + @set = Set.new(@arr) + end + + it 'empty set' do + expect(Set.new.ai).to eq([].ai) + end + + if RUBY_VERSION > '1.9' + it 'plain multiline' do + expect(@set.ai(plain: true)).to eq(@arr.ai(plain: true)) + end + + it 'plain multiline indented' do + expect(@set.ai(plain: true, indent: 1)).to eq(@arr.ai(plain: true, indent: 1)) + end + + it 'plain single line' do + expect(@set.ai(plain: true, multiline: false)).to eq(@arr.ai(plain: true, multiline: false)) + end + + it 'colored multiline (default)' do + expect(@set.ai).to eq(@arr.ai) + end + else # Prior to Ruby 1.9 the order of set values is unpredicatble. + it 'plain multiline' do + expect(@set.sort_by { |x| x.to_s }.ai(plain: true)).to eq(@arr.sort_by { |x| x.to_s }.ai(plain: true)) + end + + it 'plain multiline indented' do + expect(@set.sort_by { |x| x.to_s }.ai(plain: true, indent: 1)).to eq(@arr.sort_by { |x| x.to_s }.ai(plain: true, indent: 1)) + end + + it 'plain single line' do + expect(@set.sort_by { |x| x.to_s }.ai(plain: true, multiline: false)).to eq(@arr.sort_by { |x| x.to_s }.ai(plain: true, multiline: false)) + end + + it 'colored multiline (default)' do + expect(@set.sort_by { |x| x.to_s }.ai).to eq(@arr.sort_by { |x| x.to_s }.ai) + end + end + end +end diff --git a/spec/formatters/struct_spec.rb b/spec/formatters/struct_spec.rb new file mode 100644 index 00000000..5552ced5 --- /dev/null +++ b/spec/formatters/struct_spec.rb @@ -0,0 +1,61 @@ +require_relative '../spec_helper' + +RSpec.describe 'AwesomePrint' do + describe 'Struct' do + before do + @struct = unless defined?(Struct::SimpleStruct) + Struct.new('SimpleStruct', :name, :address).new + else + Struct::SimpleStruct.new + end + @struct.name = 'Herman Munster' + @struct.address = '1313 Mockingbird Lane' + end + + it 'empty struct' do + expect(Struct.new('EmptyStruct').ai).to eq("\e[1;33mStruct::EmptyStruct < Struct\e[0m") + end + + it 'plain multiline' do + s1 = <<-EOS.strip + address = \"1313 Mockingbird Lane\", + name = \"Herman Munster\" +EOS + s2 = <<-EOS.strip + name = \"Herman Munster\", + address = \"1313 Mockingbird Lane\" +EOS + expect(@struct.ai(plain: true)).to satisfy { |out| out.match(s1) || out.match(s2) } + end + + it 'plain multiline indented' do + s1 = <<-EOS.strip + address = "1313 Mockingbird Lane", + name = "Herman Munster" +EOS + s2 = <<-EOS.strip + name = "Herman Munster", + address = "1313 Mockingbird Lane" +EOS + expect(@struct.ai(plain: true, indent: 1)).to satisfy { |out| out.match(s1) || out.match(s2) } + end + + it 'plain single line' do + s1 = 'address = "1313 Mockingbird Lane", name = "Herman Munster"' + s2 = 'name = "Herman Munster", address = "1313 Mockingbird Lane"' + expect(@struct.ai(plain: true, multiline: false)).to satisfy { |out| out.match(s1) || out.match(s2) } + end + + it 'colored multiline (default)' do + s1 = <<-EOS.strip + address\e[0;37m = \e[0m\e[0;33m\"1313 Mockingbird Lane\"\e[0m, + name\e[0;37m = \e[0m\e[0;33m\"Herman Munster\"\e[0m +EOS + s2 = <<-EOS.strip + name\e[0;37m = \e[0m\e[0;33m\"Herman Munster\"\e[0m, + address\e[0;37m = \e[0m\e[0;33m\"1313 Mockingbird Lane\"\e[0m +EOS + expect(@struct.ai).to satisfy { |out| out.include?(s1) || out.include?(s2) } + end + end +end diff --git a/spec/merge_options_spec.rb b/spec/merge_options_spec.rb new file mode 100644 index 00000000..549455a5 --- /dev/null +++ b/spec/merge_options_spec.rb @@ -0,0 +1,13 @@ +require_relative 'spec_helper' + +RSpec.describe 'AwesomePrint' do + describe 'Utility methods' do + it 'should merge options' do + ap = AwesomePrint::Inspector.new + ap.send(:merge_options!, { color: { array: :black }, indent: 0 }) + options = ap.instance_variable_get('@options') + expect(options[:color][:array]).to eq(:black) + expect(options[:indent]).to eq(0) + end + end +end From bb5e75125b9b027b5dcf0d955531ff85b64578da Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 12:48:03 -0500 Subject: [PATCH 03/25] Further fix tests, set some formatters as core (too generic) and clean up more specs --- lib/awesome_print.rb | 1 + lib/awesome_print/colorize.rb | 2 +- lib/awesome_print/formatter.rb | 27 ++++++--- .../formatters/base_formatter.rb | 8 +++ .../formatters/bigdecimal_formatter.rb | 3 +- lib/awesome_print/formatters/dir_formatter.rb | 2 +- .../formatters/fallback_formatter.rb | 4 ++ .../formatters/method_formatter.rb | 4 ++ .../formatters/object_formatter.rb | 4 ++ .../formatters/rational_formatter.rb | 4 ++ lib/awesome_print/formatters/set_formatter.rb | 19 ++++++ .../formatters/simple_formatter.rb | 4 ++ lib/awesome_print/version.rb | 5 ++ spec/ext/nobrainer_spec.rb | 59 ------------------- spec/ext/ripple_spec.rb | 48 --------------- spec/formatters/dir_file_spec.rb | 1 + 16 files changed, 76 insertions(+), 119 deletions(-) create mode 100644 lib/awesome_print/formatters/set_formatter.rb delete mode 100644 spec/ext/nobrainer_spec.rb delete mode 100644 spec/ext/ripple_spec.rb diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index eeaa7a41..efc1e25d 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -15,6 +15,7 @@ require 'awesome_print/custom_defaults' require 'awesome_print/inspector' require 'awesome_print/formatter' + Dir["./lib/awesome_print/formatters/**/*.rb"].each { |f| require f } require 'awesome_print/version' diff --git a/lib/awesome_print/colorize.rb b/lib/awesome_print/colorize.rb index 70e3335f..0d0742dd 100644 --- a/lib/awesome_print/colorize.rb +++ b/lib/awesome_print/colorize.rb @@ -6,7 +6,7 @@ module Colorize # Pick the color and apply it to the given string as necessary. #------------------------------------------------------------------------------ def colorize(str, type) - puts "[COLORIZING] - using #{options[:color][type]} for #{type}" + puts "[COLORIZING] - using #{options[:color][type]} for #{type}" if AwesomePrint.debug str = CGI.escapeHTML(str) if options[:html] if options[:plain] || !options[:color][type] || !inspector.colorize? diff --git a/lib/awesome_print/formatter.rb b/lib/awesome_print/formatter.rb index 49cae349..c5c996b6 100644 --- a/lib/awesome_print/formatter.rb +++ b/lib/awesome_print/formatter.rb @@ -31,18 +31,27 @@ def initialize(inspector) # type is determined by Inspector#printable #------------------------------------------------------------------------------ def format(object, type = nil) - puts "[FORMAT] #{type.to_s.red} >>> #{object}" + puts "[FORMAT] #{type.to_s.red} >>> #{object}" if AwesomePrint.debug format_with = active_formatter(type) - puts "[ACTIVE] using > #{format_with.to_s.blueish} < to format" - - if format_with && format_with.send(:formattable?, object) - format_with.new(@inspector).format(object) - else - puts "[FALLBACK] well darn, we're just gonna have to fb" - # in this case, formatter is missing or fails format test - AwesomePrint::Formatters::FallbackFormatter.new(@inspector).format(object) + puts "[ACTIVE] using > #{format_with.to_s.blueish} < to format" if AwesomePrint.debug + + # if we have an active formatter, and it's good to go, lets return that + + return format_with.new(@inspector).format(object) if format_with&.formattable?(object) + + # if that's not working, lets try discover the format via formattable? + self.class.registered_formatters.each do |fmt| + puts "[FORMATTABLE] trying to use #{fmt} - #{fmt.last.core?}" if AwesomePrint.debug + next if fmt.last.core? # if it's a core level formatter, move on + + return fmt.last.new(@inspector).format(object) if fmt.last.formattable?(object) end + + # we've run out of options. lets try and coerce into something we can work + # with + puts "[FALLBACK] well darn, we're just gonna have to fb" if AwesomePrint.debug + AwesomePrint::Formatters::FallbackFormatter.new(@inspector).format(object) end def active_formatter(type) diff --git a/lib/awesome_print/formatters/base_formatter.rb b/lib/awesome_print/formatters/base_formatter.rb index 61897a11..4f67bc56 100644 --- a/lib/awesome_print/formatters/base_formatter.rb +++ b/lib/awesome_print/formatters/base_formatter.rb @@ -12,6 +12,14 @@ class BaseFormatter attr_reader :object, :inspector, :options + def self.formattable?(obj) + false + end + + def self.core? + false + end + def initialize(inspector) @inspector = inspector @options = inspector.options diff --git a/lib/awesome_print/formatters/bigdecimal_formatter.rb b/lib/awesome_print/formatters/bigdecimal_formatter.rb index a626b939..46cf2cc8 100644 --- a/lib/awesome_print/formatters/bigdecimal_formatter.rb +++ b/lib/awesome_print/formatters/bigdecimal_formatter.rb @@ -1,4 +1,5 @@ require_relative 'base_formatter' +require 'bigdecimal' module AwesomePrint module Formatters @@ -7,7 +8,7 @@ class BigdecimalFormatter < BaseFormatter formatter_for :bigdecimal def self.formattable?(object) - true + object.is_a?(BigDecimal) end def format(object) diff --git a/lib/awesome_print/formatters/dir_formatter.rb b/lib/awesome_print/formatters/dir_formatter.rb index 69bff1d1..521a641a 100644 --- a/lib/awesome_print/formatters/dir_formatter.rb +++ b/lib/awesome_print/formatters/dir_formatter.rb @@ -8,7 +8,7 @@ class DirFormatter < BaseFormatter formatter_for :dir def self.formattable?(object) - object.is_a?(Dir) + object.kind_of?(Dir) end def format(dir) diff --git a/lib/awesome_print/formatters/fallback_formatter.rb b/lib/awesome_print/formatters/fallback_formatter.rb index 083e2982..f6fd24ef 100644 --- a/lib/awesome_print/formatters/fallback_formatter.rb +++ b/lib/awesome_print/formatters/fallback_formatter.rb @@ -12,6 +12,10 @@ def self.formattable?(object) true end + def self.core? + true + end + def format(object) if @options[:raw] && object.instance_variables.any? Formatters::ObjectFormatter.new(@inspector).format(object) diff --git a/lib/awesome_print/formatters/method_formatter.rb b/lib/awesome_print/formatters/method_formatter.rb index a61312f4..af0db552 100644 --- a/lib/awesome_print/formatters/method_formatter.rb +++ b/lib/awesome_print/formatters/method_formatter.rb @@ -6,6 +6,10 @@ class MethodFormatter < BaseFormatter formatter_for :method + def self.core? + true + end + def self.formattable?(object) puts "formattable? for METHOD..." true diff --git a/lib/awesome_print/formatters/object_formatter.rb b/lib/awesome_print/formatters/object_formatter.rb index 0b0b3441..67c2bef8 100644 --- a/lib/awesome_print/formatters/object_formatter.rb +++ b/lib/awesome_print/formatters/object_formatter.rb @@ -6,6 +6,10 @@ class ObjectFormatter < BaseFormatter formatter_for :object + def self.core? + true + end + def self.formattable?(object) object.is_a?(Object) end diff --git a/lib/awesome_print/formatters/rational_formatter.rb b/lib/awesome_print/formatters/rational_formatter.rb index c91e6328..e75c25d8 100644 --- a/lib/awesome_print/formatters/rational_formatter.rb +++ b/lib/awesome_print/formatters/rational_formatter.rb @@ -6,6 +6,10 @@ class RationalFormatter < SimpleFormatter formatter_for :rational + def self.formattable?(object) + object.is_a?(Rational) + end + end end end diff --git a/lib/awesome_print/formatters/set_formatter.rb b/lib/awesome_print/formatters/set_formatter.rb new file mode 100644 index 00000000..35adfba2 --- /dev/null +++ b/lib/awesome_print/formatters/set_formatter.rb @@ -0,0 +1,19 @@ +require_relative 'base_formatter' + +module AwesomePrint + module Formatters + class SetFormatter < BaseFormatter + + formatter_for :set + + def self.formattable?(object) + object.kind_of?(Set) + end + + def format(object) + Formatters::ArrayFormatter.new(@inspector).format(object.to_a) + end + + end + end +end diff --git a/lib/awesome_print/formatters/simple_formatter.rb b/lib/awesome_print/formatters/simple_formatter.rb index 04d403ec..2aa71389 100644 --- a/lib/awesome_print/formatters/simple_formatter.rb +++ b/lib/awesome_print/formatters/simple_formatter.rb @@ -6,6 +6,10 @@ class SimpleFormatter < BaseFormatter formatter_for :simple + def self.core? + true + end + def self.formattable?(object) object.respond_to?(:to_s) end diff --git a/lib/awesome_print/version.rb b/lib/awesome_print/version.rb index bc7cf95e..f937384d 100644 --- a/lib/awesome_print/version.rb +++ b/lib/awesome_print/version.rb @@ -4,6 +4,11 @@ # See LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ module AwesomePrint + + def self.debug + false + end + def self.version '1.8.0' end diff --git a/spec/ext/nobrainer_spec.rb b/spec/ext/nobrainer_spec.rb deleted file mode 100644 index e08c83b4..00000000 --- a/spec/ext/nobrainer_spec.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'spec_helper' - -RSpec.describe 'AwesomePrint/NoBrainer', skip: -> { !ExtVerifier.has_nobrainer? }.call do - - if ExtVerifier.has_nobrainer? - before :all do - NoBrainer.configure do |config| - config.app_name = 'ap_test' - config.environment = :test - end - end - - before :all do - class SomeModel - include NoBrainer::Document - - field :first_name, type: String - field :last_name, type: String - field :some_field - end - end - - after :all do - Object.instance_eval { remove_const :SomeModel } - end - end - - before do - @ap = AwesomePrint::Inspector.new plain: true - end - - it 'should print class instance' do - user = SomeModel.new first_name: 'Al', last_name: 'Capone' - out = @ap.send :awesome, user - - object_id = user.id.inspect - str = <<-EOS.strip -# { - :id => #{object_id}, - :first_name => "Al", - :last_name => "Capone" -} - EOS - expect(out).to eq(str) - end - - it 'should print the class' do - class_spec = <<-EOS.strip -class SomeModel < Object { - :id => :string, - :first_name => :string, - :last_name => :string, - :some_field => :object -} - EOS - - expect(@ap.send(:awesome, SomeModel)).to eq class_spec - end -end diff --git a/spec/ext/ripple_spec.rb b/spec/ext/ripple_spec.rb deleted file mode 100644 index 01eef658..00000000 --- a/spec/ext/ripple_spec.rb +++ /dev/null @@ -1,48 +0,0 @@ -require 'spec_helper' - -RSpec.describe 'AwesomePrint/Ripple', skip: -> { !ExtVerifier.has_ripple? }.call do - - if ExtVerifier.has_ripple? - before :all do - class RippleUser - include Ripple::Document - - key_on :_id - property :_id, String - property :first_name, String - property :last_name, String - end - end - - after :all do - Object.instance_eval { remove_const :RippleUser } - end - end - - before do - @ap = AwesomePrint::Inspector.new plain: true, sort_keys: true - end - - it 'should print class instance' do - user = RippleUser.new _id: '12345', first_name: 'Al', last_name: 'Capone' - out = @ap.send :awesome, user - - expect(out).to be_similar_to <<-EOS.strip -# { - :_id => "12345", - :first_name => "Al", - :last_name => "Capone" -} - EOS - end - - it 'should print the class' do - expect(@ap.send(:awesome, RippleUser)).to eq <<-EOS.strip -class RippleUser < Object { - :_id => :string, - :first_name => :string, - :last_name => :string -} - EOS - end -end diff --git a/spec/formatters/dir_file_spec.rb b/spec/formatters/dir_file_spec.rb index e87d9159..c542d8ad 100644 --- a/spec/formatters/dir_file_spec.rb +++ b/spec/formatters/dir_file_spec.rb @@ -35,6 +35,7 @@ class My < Dir; end require 'tmpdir' my = My.new(Dir.tmpdir) + expect(my.ai(plain: true)).to eq("#{my.inspect}\n" << `ls -alF #{my.path}`.chop) end From 7eaf2ca2cfedf2ced23cd54d1ac7fb4754c5c915 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 12:50:21 -0500 Subject: [PATCH 04/25] remove extraneous formatters we don't want to continue supporting (ripple, nobrainer) and relo external formatters to formatters/ext --- lib/awesome_print/ext/nobrainer.rb | 52 -------------- lib/awesome_print/ext/ripple.rb | 71 ------------------- .../{ => formatters}/ext/action_view.rb | 0 .../{ => formatters}/ext/active_record.rb | 0 .../{ => formatters}/ext/active_support.rb | 0 .../{ => formatters}/ext/mongo_mapper.rb | 0 .../{ => formatters}/ext/mongoid.rb | 0 .../{ => formatters}/ext/nokogiri.rb | 0 .../{ => formatters}/ext/sequel.rb | 0 spec/{ => formatters}/methods_spec.rb | 0 spec/{ => formatters}/objects_spec.rb | 0 11 files changed, 123 deletions(-) delete mode 100644 lib/awesome_print/ext/nobrainer.rb delete mode 100644 lib/awesome_print/ext/ripple.rb rename lib/awesome_print/{ => formatters}/ext/action_view.rb (100%) rename lib/awesome_print/{ => formatters}/ext/active_record.rb (100%) rename lib/awesome_print/{ => formatters}/ext/active_support.rb (100%) rename lib/awesome_print/{ => formatters}/ext/mongo_mapper.rb (100%) rename lib/awesome_print/{ => formatters}/ext/mongoid.rb (100%) rename lib/awesome_print/{ => formatters}/ext/nokogiri.rb (100%) rename lib/awesome_print/{ => formatters}/ext/sequel.rb (100%) rename spec/{ => formatters}/methods_spec.rb (100%) rename spec/{ => formatters}/objects_spec.rb (100%) diff --git a/lib/awesome_print/ext/nobrainer.rb b/lib/awesome_print/ext/nobrainer.rb deleted file mode 100644 index 109a656e..00000000 --- a/lib/awesome_print/ext/nobrainer.rb +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -module AwesomePrint - module NoBrainer - - def self.included(base) - base.send :alias_method, :cast_without_nobrainer, :cast - base.send :alias_method, :cast, :cast_with_nobrainer - end - - # Add NoBrainer class names to the dispatcher pipeline. - #------------------------------------------------------------------------------ - def cast_with_nobrainer(object, type) - cast = cast_without_nobrainer(object, type) - if defined?(::NoBrainer::Document) - if object.is_a?(Class) && object < ::NoBrainer::Document - cast = :nobrainer_class - elsif object.is_a?(::NoBrainer::Document) - cast = :nobrainer_document - end - end - cast - end - - # Format NoBrainer class object. - #------------------------------------------------------------------------------ - def awesome_nobrainer_class(object) - name = "#{awesome_simple(object, :class)} < #{awesome_simple(object.superclass, :class)}" - data = Hash[object.fields.map do |field, options| - [field, (options[:type] || Object).to_s.underscore.to_sym] - end] - - name = "class #{awesome_simple(object.to_s, :class)}" - base = "< #{awesome_simple(object.superclass.to_s, :class)}" - - [name, base, awesome_hash(data)].join(' ') - end - - # Format NoBrainer Document object. - #------------------------------------------------------------------------------ - def awesome_nobrainer_document(object) - data = object.inspectable_attributes.symbolize_keys - data = { errors: object.errors, attributes: data } if object.errors.present? - "#{object} #{awesome_hash(data)}" - end - end -end - -AwesomePrint::Formatter.send(:include, AwesomePrint::NoBrainer) diff --git a/lib/awesome_print/ext/ripple.rb b/lib/awesome_print/ext/ripple.rb deleted file mode 100644 index e2d243ff..00000000 --- a/lib/awesome_print/ext/ripple.rb +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -module AwesomePrint - module Ripple - - def self.included(base) - base.send :alias_method, :cast_without_ripple, :cast - base.send :alias_method, :cast, :cast_with_ripple - end - - # Add Ripple class names to the dispatcher pipeline. - #------------------------------------------------------------------------------ - def cast_with_ripple(object, type) - cast = cast_without_ripple(object, type) - return cast if !defined?(::Ripple) - - if object.is_a?(::Ripple::AttributeMethods) # Module used to access attributes across documents and embedded documents - cast = :ripple_document_instance - elsif object.is_a?(::Ripple::Properties) # Used to access property metadata on Ripple classes - cast = :ripple_document_class - end - cast - end - - private - - # Format Ripple instance object. - # - # NOTE: by default only instance attributes are shown. To format a Ripple document instance - # as a regular object showing its instance variables and accessors use :raw => true option: - # - # ap document, :raw => true - # - #------------------------------------------------------------------------------ - def awesome_ripple_document_instance(object) - return object.inspect if !defined?(::ActiveSupport::OrderedHash) - return awesome_object(object) if @options[:raw] - exclude_assoc = @options[:exclude_assoc] or @options[:exclude_associations] - - data = object.attributes.inject(::ActiveSupport::OrderedHash.new) do |hash, (name, value)| - hash[name.to_sym] = object.send(name) - hash - end - - unless exclude_assoc - data = object.class.embedded_associations.inject(data) do |hash, assoc| - hash[assoc.name] = object.get_proxy(assoc) # Should always be array or Ripple::EmbeddedDocument for embedded associations - hash - end - end - - "#{object} " << awesome_hash(data) - end - - # Format Ripple class object. - #------------------------------------------------------------------------------ - def awesome_ripple_document_class(object) - return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:properties) - - name = "class #{awesome_simple(object.to_s, :class)}" - base = "< #{awesome_simple(object.superclass.to_s, :class)}" - - [name, base, awesome_hash(data)].join(' ') - end - end -end - -AwesomePrint::Formatter.send(:include, AwesomePrint::Ripple) diff --git a/lib/awesome_print/ext/action_view.rb b/lib/awesome_print/formatters/ext/action_view.rb similarity index 100% rename from lib/awesome_print/ext/action_view.rb rename to lib/awesome_print/formatters/ext/action_view.rb diff --git a/lib/awesome_print/ext/active_record.rb b/lib/awesome_print/formatters/ext/active_record.rb similarity index 100% rename from lib/awesome_print/ext/active_record.rb rename to lib/awesome_print/formatters/ext/active_record.rb diff --git a/lib/awesome_print/ext/active_support.rb b/lib/awesome_print/formatters/ext/active_support.rb similarity index 100% rename from lib/awesome_print/ext/active_support.rb rename to lib/awesome_print/formatters/ext/active_support.rb diff --git a/lib/awesome_print/ext/mongo_mapper.rb b/lib/awesome_print/formatters/ext/mongo_mapper.rb similarity index 100% rename from lib/awesome_print/ext/mongo_mapper.rb rename to lib/awesome_print/formatters/ext/mongo_mapper.rb diff --git a/lib/awesome_print/ext/mongoid.rb b/lib/awesome_print/formatters/ext/mongoid.rb similarity index 100% rename from lib/awesome_print/ext/mongoid.rb rename to lib/awesome_print/formatters/ext/mongoid.rb diff --git a/lib/awesome_print/ext/nokogiri.rb b/lib/awesome_print/formatters/ext/nokogiri.rb similarity index 100% rename from lib/awesome_print/ext/nokogiri.rb rename to lib/awesome_print/formatters/ext/nokogiri.rb diff --git a/lib/awesome_print/ext/sequel.rb b/lib/awesome_print/formatters/ext/sequel.rb similarity index 100% rename from lib/awesome_print/ext/sequel.rb rename to lib/awesome_print/formatters/ext/sequel.rb diff --git a/spec/methods_spec.rb b/spec/formatters/methods_spec.rb similarity index 100% rename from spec/methods_spec.rb rename to spec/formatters/methods_spec.rb diff --git a/spec/objects_spec.rb b/spec/formatters/objects_spec.rb similarity index 100% rename from spec/objects_spec.rb rename to spec/formatters/objects_spec.rb From 102d254628ca0a2375024be63e7b1514732db5e9 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 13:00:36 -0500 Subject: [PATCH 05/25] Remove extraneous/superflous copyright duplicates --- README.md | 9 --------- awesome_print.gemspec | 6 ------ lib/ap.rb | 6 ------ lib/awesome_print.rb | 13 ------------- lib/awesome_print/core_ext/awesome_method_array.rb | 6 ------ lib/awesome_print/core_ext/class.rb | 5 ----- lib/awesome_print/core_ext/kernel.rb | 5 ----- lib/awesome_print/core_ext/logger.rb | 5 ----- lib/awesome_print/core_ext/method.rb | 6 ------ lib/awesome_print/core_ext/object.rb | 5 ----- lib/awesome_print/core_ext/string.rb | 5 ----- lib/awesome_print/formatters/ext/action_view.rb | 5 ----- lib/awesome_print/formatters/ext/active_record.rb | 5 ----- lib/awesome_print/formatters/ext/active_support.rb | 5 ----- lib/awesome_print/formatters/ext/mongo_mapper.rb | 5 ----- lib/awesome_print/formatters/ext/mongoid.rb | 5 ----- lib/awesome_print/formatters/ext/nokogiri.rb | 5 ----- lib/awesome_print/formatters/ext/sequel.rb | 5 ----- lib/awesome_print/inspector.rb | 5 ----- lib/awesome_print/version.rb | 5 ----- rails/init.rb | 6 ------ spec/spec_helper.rb | 6 ------ 22 files changed, 128 deletions(-) diff --git a/README.md b/README.md index 71609325..73e1cd1c 100644 --- a/README.md +++ b/README.md @@ -333,20 +333,11 @@ AwesomePrint.defaults = { ``` ## Versioning - AwesomePrint follows the [Semantic Versioning](http://semver.org/) standard. ### Contributing ### See [CONTRIBUTING.md](CONTRIBUTING.md) for information. -### License ### -Copyright (c) 2010-2016 Michael Dvorkin and contributors - -http://www.dvorkin.net - -%w(mike dvorkin.net) * "@" || "twitter.com/mid" - -Released under the MIT license. See LICENSE file for details. [gem_version_badge]: https://img.shields.io/gem/v/awesome_print.svg?style=flat [gem_downloads_badge]: http://img.shields.io/gem/dt/awesome_print.svg?style=flat diff --git a/awesome_print.gemspec b/awesome_print.gemspec index 735a7eac..0ebbef68 100644 --- a/awesome_print.gemspec +++ b/awesome_print.gemspec @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ - $:.push File.expand_path('../lib', __FILE__) require 'awesome_print/version' diff --git a/lib/ap.rb b/lib/ap.rb index 1cf48c21..f999691e 100644 --- a/lib/ap.rb +++ b/lib/ap.rb @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -# # Keeping this for backwards compatibility to allow # require "ap" # diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index efc1e25d..eb565df9 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -# # AwesomePrint might be loaded implicitly through ~/.irbrc or ~/.pryrc # so do nothing for subsequent requires. # @@ -34,11 +28,4 @@ # require 'awesome_print/ext/action_view' # end # end - # require 'awesome_print/ext/mongo_mapper' if defined?(MongoMapper) - # require 'awesome_print/ext/mongoid' if defined?(Mongoid) - # require 'awesome_print/ext/nokogiri' if defined?(Nokogiri) - # require 'awesome_print/ext/nobrainer' if defined?(NoBrainer) - # require 'awesome_print/ext/ripple' if defined?(Ripple) - # require 'awesome_print/ext/sequel' if defined?(Sequel) - # require 'awesome_print/ext/ostruct' if defined?(OpenStruct) end diff --git a/lib/awesome_print/core_ext/awesome_method_array.rb b/lib/awesome_print/core_ext/awesome_method_array.rb index b05dbf32..ec8d6b92 100644 --- a/lib/awesome_print/core_ext/awesome_method_array.rb +++ b/lib/awesome_print/core_ext/awesome_method_array.rb @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -# # The following makes it possible to invoke awesome_print while performing # operations on method arrays, ex: # diff --git a/lib/awesome_print/core_ext/class.rb b/lib/awesome_print/core_ext/class.rb index 7747b5a1..190e3207 100644 --- a/lib/awesome_print/core_ext/class.rb +++ b/lib/awesome_print/core_ext/class.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ class Class #:nodoc: # # Intercept methods below to inject @__awesome_print__ instance variable diff --git a/lib/awesome_print/core_ext/kernel.rb b/lib/awesome_print/core_ext/kernel.rb index e8d38edd..bb87daa7 100644 --- a/lib/awesome_print/core_ext/kernel.rb +++ b/lib/awesome_print/core_ext/kernel.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module Kernel def ai(options = {}) diff --git a/lib/awesome_print/core_ext/logger.rb b/lib/awesome_print/core_ext/logger.rb index 5754ff5f..05809a1c 100644 --- a/lib/awesome_print/core_ext/logger.rb +++ b/lib/awesome_print/core_ext/logger.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module Logger diff --git a/lib/awesome_print/core_ext/method.rb b/lib/awesome_print/core_ext/method.rb index c0f14dad..02b72355 100644 --- a/lib/awesome_print/core_ext/method.rb +++ b/lib/awesome_print/core_ext/method.rb @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -# # Method#name was intorduced in Ruby 1.8.7 so we define it here as necessary. # unless nil.method(:class).respond_to?(:name) diff --git a/lib/awesome_print/core_ext/object.rb b/lib/awesome_print/core_ext/object.rb index f3685bf0..442577c0 100644 --- a/lib/awesome_print/core_ext/object.rb +++ b/lib/awesome_print/core_ext/object.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ class Object #:nodoc: # # Intercept methods below to inject @__awesome_print__ instance variable diff --git a/lib/awesome_print/core_ext/string.rb b/lib/awesome_print/core_ext/string.rb index ef590f05..4e4269bc 100644 --- a/lib/awesome_print/core_ext/string.rb +++ b/lib/awesome_print/core_ext/string.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ class String # # ANSI color codes: diff --git a/lib/awesome_print/formatters/ext/action_view.rb b/lib/awesome_print/formatters/ext/action_view.rb index 7ceaa9bc..28d373bb 100644 --- a/lib/awesome_print/formatters/ext/action_view.rb +++ b/lib/awesome_print/formatters/ext/action_view.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module ActionView # Use HTML colors and add default "debug_dump" class to the resulting HTML. diff --git a/lib/awesome_print/formatters/ext/active_record.rb b/lib/awesome_print/formatters/ext/active_record.rb index 2a4a3627..7f31be73 100644 --- a/lib/awesome_print/formatters/ext/active_record.rb +++ b/lib/awesome_print/formatters/ext/active_record.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module ActiveRecord diff --git a/lib/awesome_print/formatters/ext/active_support.rb b/lib/awesome_print/formatters/ext/active_support.rb index 2f20363d..ba2a730b 100644 --- a/lib/awesome_print/formatters/ext/active_support.rb +++ b/lib/awesome_print/formatters/ext/active_support.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module ActiveSupport diff --git a/lib/awesome_print/formatters/ext/mongo_mapper.rb b/lib/awesome_print/formatters/ext/mongo_mapper.rb index fd6e801b..943d6882 100644 --- a/lib/awesome_print/formatters/ext/mongo_mapper.rb +++ b/lib/awesome_print/formatters/ext/mongo_mapper.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module MongoMapper diff --git a/lib/awesome_print/formatters/ext/mongoid.rb b/lib/awesome_print/formatters/ext/mongoid.rb index 5a427eb7..a11987ce 100644 --- a/lib/awesome_print/formatters/ext/mongoid.rb +++ b/lib/awesome_print/formatters/ext/mongoid.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module Mongoid diff --git a/lib/awesome_print/formatters/ext/nokogiri.rb b/lib/awesome_print/formatters/ext/nokogiri.rb index fe7fc9d7..1cb385f9 100644 --- a/lib/awesome_print/formatters/ext/nokogiri.rb +++ b/lib/awesome_print/formatters/ext/nokogiri.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module Nokogiri diff --git a/lib/awesome_print/formatters/ext/sequel.rb b/lib/awesome_print/formatters/ext/sequel.rb index d45129e3..d1248659 100644 --- a/lib/awesome_print/formatters/ext/sequel.rb +++ b/lib/awesome_print/formatters/ext/sequel.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint module Sequel diff --git a/lib/awesome_print/inspector.rb b/lib/awesome_print/inspector.rb index a98b2d7f..c7aeeeb0 100644 --- a/lib/awesome_print/inspector.rb +++ b/lib/awesome_print/inspector.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ require_relative 'indentator' module AwesomePrint diff --git a/lib/awesome_print/version.rb b/lib/awesome_print/version.rb index f937384d..adb4285f 100644 --- a/lib/awesome_print/version.rb +++ b/lib/awesome_print/version.rb @@ -1,8 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ module AwesomePrint def self.debug diff --git a/rails/init.rb b/rails/init.rb index 3e6db21e..076e9f68 100644 --- a/rails/init.rb +++ b/rails/init.rb @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -# # Load awesome_print when installed as Rails 2.3.x plugin. # require File.join(File.dirname(__FILE__), '..', 'init') unless defined?(AwesomePrint) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index a31568f0..e806a030 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,9 +1,3 @@ -# Copyright (c) 2010-2016 Michael Dvorkin and contributors -# -# Awesome Print is freely distributable under the terms of MIT license. -# See LICENSE file or http://www.opensource.org/licenses/mit-license.php -#------------------------------------------------------------------------------ -# # Running specs from the command line: # $ rake spec # Entire spec suite. # $ rspec spec/objects_spec.rb # Individual spec file. From 32e7efd20c166fabf2f5dd101992c583bbc77364 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 13:01:44 -0500 Subject: [PATCH 06/25] Remove rails 2.x plugin style accessor --- init.rb | 1 - rails/init.rb | 3 --- 2 files changed, 4 deletions(-) delete mode 100644 init.rb delete mode 100644 rails/init.rb diff --git a/init.rb b/init.rb deleted file mode 100644 index 2c63a886..00000000 --- a/init.rb +++ /dev/null @@ -1 +0,0 @@ -require File.join(File.dirname(__FILE__), 'lib', 'awesome_print') diff --git a/rails/init.rb b/rails/init.rb deleted file mode 100644 index 076e9f68..00000000 --- a/rails/init.rb +++ /dev/null @@ -1,3 +0,0 @@ -# Load awesome_print when installed as Rails 2.3.x plugin. -# -require File.join(File.dirname(__FILE__), '..', 'init') unless defined?(AwesomePrint) From 856f8c477c69d632395eb143ed5434b397251c64 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 13:02:07 -0500 Subject: [PATCH 07/25] Remove the require 'ap' mechanic. --- lib/ap.rb | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 lib/ap.rb diff --git a/lib/ap.rb b/lib/ap.rb deleted file mode 100644 index f999691e..00000000 --- a/lib/ap.rb +++ /dev/null @@ -1,4 +0,0 @@ -# Keeping this for backwards compatibility to allow -# require "ap" -# -require File.dirname(__FILE__) + '/awesome_print' From e2bc9c2a03249cd371993474f42bf5458a5aecbb Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 13:02:39 -0500 Subject: [PATCH 08/25] not going to support 1.x ruby anymore --- lib/awesome_print.rb | 2 +- lib/awesome_print/core_ext/method.rb | 15 --------------- 2 files changed, 1 insertion(+), 16 deletions(-) delete mode 100644 lib/awesome_print/core_ext/method.rb diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index eb565df9..b024e5d2 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -2,7 +2,7 @@ # so do nothing for subsequent requires. # unless defined?(AwesomePrint::Inspector) - %w(awesome_method_array string method object class kernel).each do |file| + %w(awesome_method_array string object class kernel).each do |file| require "awesome_print/core_ext/#{file}" end diff --git a/lib/awesome_print/core_ext/method.rb b/lib/awesome_print/core_ext/method.rb deleted file mode 100644 index 02b72355..00000000 --- a/lib/awesome_print/core_ext/method.rb +++ /dev/null @@ -1,15 +0,0 @@ -# Method#name was intorduced in Ruby 1.8.7 so we define it here as necessary. -# -unless nil.method(:class).respond_to?(:name) - class Method - def name - inspect.split(/[#.>]/)[-1] - end - end - - class UnboundMethod - def name - inspect.split(/[#.>]/)[-1] - end - end -end From f0ed2e219aeae46c48f2c411aa636200239ea8fe Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 16:04:42 -0500 Subject: [PATCH 09/25] Make external formatters (Rails, etc) format as expected) --- lib/awesome_print.rb | 22 +--- lib/awesome_print/core_ext/active_support.rb | 7 ++ .../formatters/ext/action_view.rb | 17 --- .../ext/active_model_error_formatter.rb | 44 +++++++ .../formatters/ext/active_record.rb | 98 --------------- .../ext/active_record_class_formatter.rb | 43 +++++++ .../ext/active_record_instance_formatter.rb | 48 +++++++ .../ext/active_record_relation_formatter.rb | 19 +++ .../formatters/ext/active_support.rb | 42 ------- .../formatters/ext/bson_objectid_formatter.rb | 20 +++ .../hash_with_indifferent_access_formatter.rb | 20 +++ .../formatters/ext/mongo_mapper.rb | 119 ------------------ .../ext/mongo_mapper_association_formatter.rb | 31 +++++ .../ext/mongo_mapper_class_formatter.rb | 41 ++++++ .../ext/mongo_mapper_instance_formatter.rb | 67 ++++++++++ lib/awesome_print/formatters/ext/mongoid.rb | 62 --------- .../ext/mongoid_document_formatter.rb | 56 +++++++++ lib/awesome_print/formatters/ext/nokogiri.rb | 40 ------ .../formatters/ext/nokogiri_node_formatter.rb | 29 +++++ .../ext/nokogiri_nodeset_formatter.rb | 32 +++++ lib/awesome_print/formatters/ext/sequel.rb | 53 -------- .../ext/sequel_dataset_formatter.rb | 20 +++ .../ext/sequel_model_class_formatter.rb | 25 ++++ .../formatters/ext/sequel_model_formatter.rb | 26 ++++ .../ext/time_with_zone_formatter.rb | 21 ++++ spec/ext/action_view_spec.rb | 18 --- .../ext/active_record_spec.rb | 0 .../ext/active_support_spec.rb | 0 .../{ => formatters}/ext/mongo_mapper_spec.rb | 0 spec/{ => formatters}/ext/mongoid_spec.rb | 0 spec/{ => formatters}/ext/nokogiri_spec.rb | 0 31 files changed, 553 insertions(+), 467 deletions(-) create mode 100644 lib/awesome_print/core_ext/active_support.rb delete mode 100644 lib/awesome_print/formatters/ext/action_view.rb create mode 100644 lib/awesome_print/formatters/ext/active_model_error_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/active_record.rb create mode 100644 lib/awesome_print/formatters/ext/active_record_class_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/active_record_instance_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/active_record_relation_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/active_support.rb create mode 100644 lib/awesome_print/formatters/ext/bson_objectid_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/hash_with_indifferent_access_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/mongo_mapper.rb create mode 100644 lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/mongoid.rb create mode 100644 lib/awesome_print/formatters/ext/mongoid_document_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/nokogiri.rb create mode 100644 lib/awesome_print/formatters/ext/nokogiri_node_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/sequel.rb create mode 100644 lib/awesome_print/formatters/ext/sequel_dataset_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/sequel_model_class_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/sequel_model_formatter.rb create mode 100644 lib/awesome_print/formatters/ext/time_with_zone_formatter.rb delete mode 100644 spec/ext/action_view_spec.rb rename spec/{ => formatters}/ext/active_record_spec.rb (100%) rename spec/{ => formatters}/ext/active_support_spec.rb (100%) rename spec/{ => formatters}/ext/mongo_mapper_spec.rb (100%) rename spec/{ => formatters}/ext/mongoid_spec.rb (100%) rename spec/{ => formatters}/ext/nokogiri_spec.rb (100%) diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index b024e5d2..7200b532 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -2,30 +2,16 @@ # so do nothing for subsequent requires. # unless defined?(AwesomePrint::Inspector) - %w(awesome_method_array string object class kernel).each do |file| + %w(active_support awesome_method_array string object class kernel).each do |file| require "awesome_print/core_ext/#{file}" end + require 'awesome_print/version' + require 'awesome_print/core_ext/logger' if defined?(Logger) + require 'awesome_print/custom_defaults' require 'awesome_print/inspector' require 'awesome_print/formatter' Dir["./lib/awesome_print/formatters/**/*.rb"].each { |f| require f } - - require 'awesome_print/version' - require 'awesome_print/core_ext/logger' if defined?(Logger) - # - # Load the following under normal circumstances as well as in Rails - # console when required from ~/.irbrc or ~/.pryrc. - # - # require 'awesome_print/ext/active_record' if defined?(ActiveRecord) || AwesomePrint.rails_console? - # require 'awesome_print/ext/active_support' if defined?(ActiveSupport) || AwesomePrint.rails_console? - # # - # # Load remaining extensions. - # # - # if defined?(ActiveSupport.on_load) - # ActiveSupport.on_load(:action_view) do - # require 'awesome_print/ext/action_view' - # end - # end end diff --git a/lib/awesome_print/core_ext/active_support.rb b/lib/awesome_print/core_ext/active_support.rb new file mode 100644 index 00000000..93906ad2 --- /dev/null +++ b/lib/awesome_print/core_ext/active_support.rb @@ -0,0 +1,7 @@ +# +# Colorize Rails logs. +# +if defined?(ActiveSupport::LogSubscriber) + AwesomePrint.force_colors! ActiveSupport::LogSubscriber.colorize_logging +end + diff --git a/lib/awesome_print/formatters/ext/action_view.rb b/lib/awesome_print/formatters/ext/action_view.rb deleted file mode 100644 index 28d373bb..00000000 --- a/lib/awesome_print/formatters/ext/action_view.rb +++ /dev/null @@ -1,17 +0,0 @@ -module AwesomePrint - module ActionView - # Use HTML colors and add default "debug_dump" class to the resulting HTML. - def ap_debug(object, options = {}) - object.ai( - options.merge(html: true) - ).sub( - /^])/, - '
 true option:
-    #
-    # ap record, :raw => true
-    #
-    #------------------------------------------------------------------------------
-    def awesome_active_record_instance(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash)
-      return awesome_object(object) if @options[:raw]
-
-      data = if object.class.column_names != object.attributes.keys
-               object.attributes
-             else
-               object.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
-                 if object.has_attribute?(name) || object.new_record?
-                   value = object.respond_to?(name) ? object.send(name) : object.read_attribute(name)
-                   hash[name.to_sym] = value
-                 end
-                 hash
-               end
-             end
-      "#{object} " << awesome_hash(data)
-    end
-
-    # Format ActiveRecord class object.
-    #------------------------------------------------------------------------------
-    def awesome_active_record_class(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:columns) || object.to_s == 'ActiveRecord::Base'
-      return awesome_class(object) if object.respond_to?(:abstract_class?) && object.abstract_class?
-
-      data = object.columns.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
-        hash[c.name.to_sym] = c.type
-        hash
-      end
-
-      name = "class #{awesome_simple(object.to_s, :class)}"
-      base = "< #{awesome_simple(object.superclass.to_s, :class)}"
-
-      [name, base, awesome_hash(data)].join(' ')
-    end
-
-    # Format ActiveModel error object.
-    #------------------------------------------------------------------------------
-    def awesome_active_model_error(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash)
-      return awesome_object(object) if @options[:raw]
-
-      object_dump = object.marshal_dump.first
-      data = if object_dump.class.column_names != object_dump.attributes.keys
-               object_dump.attributes
-             else
-               object_dump.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
-                 if object_dump.has_attribute?(name) || object_dump.new_record?
-                   value = object_dump.respond_to?(name) ? object_dump.send(name) : object_dump.read_attribute(name)
-                   hash[name.to_sym] = value
-                 end
-                 hash
-               end
-             end
-
-      data.merge!({details: object.details, messages: object.messages})
-      "#{object} " << awesome_hash(data)
-    end
-  end
-end
-
-AwesomePrint::Formatter.send(:include, AwesomePrint::ActiveRecord)
diff --git a/lib/awesome_print/formatters/ext/active_record_class_formatter.rb b/lib/awesome_print/formatters/ext/active_record_class_formatter.rb
new file mode 100644
index 00000000..d733b397
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/active_record_class_formatter.rb
@@ -0,0 +1,43 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class ActiveRecordClassFormatter < BaseFormatter
+
+      formatter_for :active_record_class
+
+      def self.formattable?(object)
+        defined?(::ActiveRecord) &&
+          (object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base))
+      end
+
+      def format(object)
+        if @options[:raw]
+          return Formatters::ObjectFormatter.new(@inspector).format(object)
+        end
+
+        if object.respond_to?(:abstract_class?) && object.abstract_class?
+          return Formatters::ClassFormatter.new(@inspector).format(object)
+        end
+
+        if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:columns)
+          return Formatters::SimpleFormatter.new(@inspector).format(object.inspect)
+        end
+
+
+        data = object.columns.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
+          hash[c.name.to_sym] = c.type
+          hash
+        end
+
+        [
+          "class #{colorize(object.to_s, :class)}",
+          "< #{colorize(object.superclass.to_s, :class)}",
+          Formatters::HashFormatter.new(@inspector).format(data)
+        ].join(' ')
+
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/active_record_instance_formatter.rb b/lib/awesome_print/formatters/ext/active_record_instance_formatter.rb
new file mode 100644
index 00000000..74039266
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/active_record_instance_formatter.rb
@@ -0,0 +1,48 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class ActiveRecordInstanceFormatter < BaseFormatter
+
+      formatter_for :active_record_instance
+
+      def self.formattable?(object)
+        defined?(::ActiveRecord) && object.is_a?(::ActiveRecord::Base)
+      end
+
+      # Format ActiveRecord instance object.
+      #
+      # NOTE: by default only instance attributes (i.e. columns) are shown. To format
+      # ActiveRecord instance as regular object showing its instance variables and
+      # accessors use :raw => true option:
+      #
+      # ap record, :raw => true
+      #
+      #------------------------------------------------------------------------------
+      def format(object)
+        if @options[:raw]
+          return Formatters::ObjectFormatter.new(@inspector).format(object)
+        end
+
+        if !defined?(::ActiveSupport::OrderedHash)
+          return Formatters::SimpleFormatter.new(@inspector).format(object.inspect)
+        end
+
+        if object.class.column_names != object.attributes.keys
+          data = object.attributes
+        else
+          data = object.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
+            if object.has_attribute?(name) || object.new_record?
+              value = object.respond_to?(name) ? object.send(name) : object.read_attribute(name)
+              hash[name.to_sym] = value
+            end
+            hash
+          end
+        end
+
+        "#{object} " << Formatters::HashFormatter.new(@inspector).format(data)
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/active_record_relation_formatter.rb b/lib/awesome_print/formatters/ext/active_record_relation_formatter.rb
new file mode 100644
index 00000000..fcd5117a
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/active_record_relation_formatter.rb
@@ -0,0 +1,19 @@
+require_relative '../array_formatter'
+
+module AwesomePrint
+  module Formatters
+    class ActiveRecordRelationFormatter < ArrayFormatter
+
+      formatter_for :active_record_relation
+
+      def self.core?
+        false
+      end
+
+      def self.formattable?(object)
+        defined?(::ActiveRecord) && object.class.ancestors.include?(::ActiveRecord::Relation)
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/active_support.rb b/lib/awesome_print/formatters/ext/active_support.rb
deleted file mode 100644
index ba2a730b..00000000
--- a/lib/awesome_print/formatters/ext/active_support.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-module AwesomePrint
-  module ActiveSupport
-
-    def self.included(base)
-      base.send :alias_method, :cast_without_active_support, :cast
-      base.send :alias_method, :cast, :cast_with_active_support
-    end
-
-    def cast_with_active_support(object, type)
-      cast = cast_without_active_support(object, type)
-      if defined?(::ActiveSupport) && defined?(::HashWithIndifferentAccess)
-        if (defined?(::ActiveSupport::TimeWithZone) && object.is_a?(::ActiveSupport::TimeWithZone)) || object.is_a?(::Date)
-          cast = :active_support_time
-        elsif object.is_a?(::HashWithIndifferentAccess)
-          cast = :hash_with_indifferent_access
-        end
-      end
-      cast
-    end
-
-    # Format ActiveSupport::TimeWithZone as standard Time.
-    #------------------------------------------------------------------------------
-    def awesome_active_support_time(object)
-      colorize(object.inspect, :time)
-    end
-
-    # Format HashWithIndifferentAccess as standard Hash.
-    #------------------------------------------------------------------------------
-    def awesome_hash_with_indifferent_access(object)
-      awesome_hash(object)
-    end
-  end
-end
-
-AwesomePrint::Formatter.send(:include, AwesomePrint::ActiveSupport)
-#
-# Colorize Rails logs.
-#
-if defined?(ActiveSupport::LogSubscriber)
-  AwesomePrint.force_colors! ActiveSupport::LogSubscriber.colorize_logging
-end
-
diff --git a/lib/awesome_print/formatters/ext/bson_objectid_formatter.rb b/lib/awesome_print/formatters/ext/bson_objectid_formatter.rb
new file mode 100644
index 00000000..e6e99497
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/bson_objectid_formatter.rb
@@ -0,0 +1,20 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class BsonObjectidFormatter < BaseFormatter
+
+      formatter_for :bson_objectid
+
+      def self.formattable?(object)
+        (defined?(::BSON) && object.is_a?(::BSON::ObjectId)) ||
+          (defined?(::Moped::BSON) && object.is_a?(::Moped::BSON::ObjectId))
+      end
+
+      def format(object)
+        colorize(object.inspect, self.class.formatted_object_type)
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/hash_with_indifferent_access_formatter.rb b/lib/awesome_print/formatters/ext/hash_with_indifferent_access_formatter.rb
new file mode 100644
index 00000000..b6444f6e
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/hash_with_indifferent_access_formatter.rb
@@ -0,0 +1,20 @@
+require_relative '../hash_formatter'
+
+module AwesomePrint
+  module Formatters
+    class HashWithIndifferentAccessFormatter < HashFormatter
+
+      formatter_for :hash_with_indifferent_access
+
+      def self.core?
+        false
+      end
+
+      def self.formattable?(object)
+        defined?(::HashWithIndifferentAccess) &&
+          object.is_a?(::HashWithIndifferentAccess)
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/mongo_mapper.rb b/lib/awesome_print/formatters/ext/mongo_mapper.rb
deleted file mode 100644
index 943d6882..00000000
--- a/lib/awesome_print/formatters/ext/mongo_mapper.rb
+++ /dev/null
@@ -1,119 +0,0 @@
-module AwesomePrint
-  module MongoMapper
-
-    def self.included(base)
-      base.send :alias_method, :cast_without_mongo_mapper, :cast
-      base.send :alias_method, :cast, :cast_with_mongo_mapper
-    end
-
-    # Add MongoMapper class names to the dispatcher pipeline.
-    #------------------------------------------------------------------------------
-    def cast_with_mongo_mapper(object, type)
-      apply_default_mongo_mapper_options
-      cast = cast_without_mongo_mapper(object, type)
-
-      if defined?(::MongoMapper::Document)
-        if object.is_a?(Class) && (object.ancestors & [::MongoMapper::Document, ::MongoMapper::EmbeddedDocument]).size > 0
-          cast = :mongo_mapper_class
-        elsif object.is_a?(::MongoMapper::Document) || object.is_a?(::MongoMapper::EmbeddedDocument)
-          cast = :mongo_mapper_instance
-        elsif object.is_a?(::MongoMapper::Plugins::Associations::Base)
-          cast = :mongo_mapper_association
-        elsif object.is_a?(::BSON::ObjectId)
-          cast = :mongo_mapper_bson_id
-        end
-      end
-
-      cast
-    end
-
-    # Format MongoMapper class object.
-    #------------------------------------------------------------------------------
-    def awesome_mongo_mapper_class(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:keys)
-
-      data = object.keys.sort.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
-        hash[c.first] = (c.last.type || 'undefined').to_s.underscore.intern
-        hash
-      end
-
-      # Add in associations
-      if @options[:mongo_mapper][:show_associations]
-        object.associations.each do |name, assoc|
-          data[name.to_s] = assoc
-        end
-      end
-
-      name = "class #{awesome_simple(object.to_s, :class)}"
-      base = "< #{awesome_simple(object.superclass.to_s, :class)}"
-
-      [name, base, awesome_hash(data)].join(' ')
-    end
-
-    # Format MongoMapper instance object.
-    #
-    # NOTE: by default only instance attributes (i.e. keys) are shown. To format
-    # MongoMapper instance as regular object showing its instance variables and
-    # accessors use :raw => true option:
-    #
-    # ap record, :raw => true
-    #
-    #------------------------------------------------------------------------------
-    def awesome_mongo_mapper_instance(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash)
-      return awesome_object(object) if @options[:raw]
-
-      data = object.keys.keys.sort_by { |k| k }.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
-        hash[name] = object[name]
-        hash
-      end
-
-      # Add in associations
-      if @options[:mongo_mapper][:show_associations]
-        object.associations.each do |name, assoc|
-          data[name.to_s] = if @options[:mongo_mapper][:inline_embedded] and assoc.embeddable?
-                              object.send(name)
-                            else
-                              assoc
-                            end
-        end
-      end
-
-      label = object.to_s
-      label = "#{colorize('embedded', :assoc)} #{label}" if object.is_a?(::MongoMapper::EmbeddedDocument)
-
-      "#{label} " << awesome_hash(data)
-    end
-
-    # Format MongoMapper association object.
-    #------------------------------------------------------------------------------
-    def awesome_mongo_mapper_association(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash)
-      return awesome_object(object) if @options[:raw]
-
-      association = object.class.name.split('::').last.titleize.downcase.sub(/ association$/, '')
-      association = "embeds #{association}" if object.embeddable?
-      class_name = object.class_name
-
-      "#{colorize(association, :assoc)} #{colorize(class_name, :class)}"
-    end
-
-    # Format BSON::ObjectId
-    #------------------------------------------------------------------------------
-    def awesome_mongo_mapper_bson_id(object)
-      object.inspect
-    end
-
-    private
-
-    def apply_default_mongo_mapper_options
-      @options[:color][:assoc] ||= :greenish
-      @options[:mongo_mapper]  ||= {
-        show_associations: false, # Display association data for MongoMapper documents and classes.
-        inline_embedded: false    # Display embedded associations inline with MongoMapper documents.
-      }
-    end
-  end
-end
-
-AwesomePrint::Formatter.send(:include, AwesomePrint::MongoMapper)
diff --git a/lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb b/lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb
new file mode 100644
index 00000000..ff0915f0
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb
@@ -0,0 +1,31 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class MongoMapperClassFormatter < BaseFormatter
+
+      formatter_for :mongo_mapper_association
+
+      def self.formattable?(object)
+        defined?(::MongoMapper) && object.is_a?(::MongoMapper::Plugins::Associations::Base)
+      end
+
+      def format(object)
+        if @options[:raw]
+          return Formatters::ObjectFormatter.new(@inspector).format(object)
+        end
+
+        if !defined?(::ActiveSupport::OrderedHash)
+          return Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s)
+        end
+
+        association = object.class.name.split('::').last.titleize.downcase.sub(/ association$/, '')
+        association = "embeds #{association}" if object.embeddable?
+        class_name = object.class_name
+
+        "#{colorize(association, :assoc)} #{colorize(class_name, :class)}"
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb b/lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb
new file mode 100644
index 00000000..7e2b3989
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb
@@ -0,0 +1,41 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class MongoMapperClassFormatter < BaseFormatter
+
+      formatter_for :mongo_mapper_class
+
+      def self.formattable?(object)
+        defined?(::MongoMapper) &&
+          object.is_a?(Class) &&
+          (object.ancestors & [::MongoMapper::Document, ::MongoMapper::EmbeddedDocument]).size > 0
+      end
+
+      def format(object)
+      unless defined?(::ActiveSupport::OrderedHash) && object.respond_to?(:keys)
+        return Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s)
+      end
+
+      data = object.keys.sort.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
+        hash[c.first] = (c.last.type || 'undefined').to_s.underscore.to_sym
+        hash
+      end
+
+      # Add in associations
+      if @options[:mongo_mapper][:show_associations]
+        object.associations.each { |name, assoc| data[name.to_s] = assoc }
+      end
+
+      sf = Formatters::SimpleFormatter.new(@inspector)
+
+      [
+        "class #{sf.format(object.to_s, :class)}",
+        "< #{sf.format(object.superclass.to_s, :class)}",
+        Formatters::HashFormatter.new(@inspector).format(data)
+      ].join(' ')
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb b/lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb
new file mode 100644
index 00000000..fc208d27
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb
@@ -0,0 +1,67 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class MongoMapperInstanceFormatter < BaseFormatter
+
+      formatter_for :mongo_mapper_instance
+
+      def self.formattable?(object)
+        defined?(::MongoMapper) &&
+          (object.is_a?(::MongoMapper::Document) ||
+          object.is_a?(::MongoMapper::EmbeddedDocument))
+      end
+
+      def initialize(inspector)
+        super(inspector)
+
+        @options[:color][:assoc] ||= :greenish
+        @options[:mongo_mapper]  ||= {
+          show_associations: false, # Display association data for MongoMapper documents and classes.
+          inline_embedded: false    # Display embedded associations inline with MongoMapper documents.
+        }
+      end
+
+      # Format MongoMapper instance object.
+      #
+      # NOTE: by default only instance attributes (i.e. keys) are shown. To format
+      # MongoMapper instance as regular object showing its instance variables and
+      # accessors use :raw => true option:
+      #
+      # ap record, :raw => true
+      #
+      #------------------------------------------------------------------------------
+      def format(object)
+        if @options[:raw]
+          return Formatters::ObjectFormatter.new(@inspector).format(object)
+        end
+
+        if !defined?(::ActiveSupport::OrderedHash)
+          return Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s)
+        end
+
+        data = object.keys.keys.sort_by { |k| k }.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
+          hash[name] = object[name]
+          hash
+        end
+
+        # Add in associations
+        if @options[:mongo_mapper][:show_associations]
+          object.associations.each do |name, assoc|
+            data[name.to_s] = if @options[:mongo_mapper][:inline_embedded] and assoc.embeddable?
+                                object.send(name)
+                              else
+                                assoc
+                              end
+          end
+        end
+
+        label = object.to_s
+        label = "#{colorize('embedded', :assoc)} #{label}" if object.is_a?(::MongoMapper::EmbeddedDocument)
+
+        "#{label} " << Formatters::HashFormatter.new(@inspector).format(data)
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/mongoid.rb b/lib/awesome_print/formatters/ext/mongoid.rb
deleted file mode 100644
index a11987ce..00000000
--- a/lib/awesome_print/formatters/ext/mongoid.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-module AwesomePrint
-  module Mongoid
-
-    def self.included(base)
-      base.send :alias_method, :cast_without_mongoid, :cast
-      base.send :alias_method, :cast, :cast_with_mongoid
-    end
-
-    # Add Mongoid class names to the dispatcher pipeline.
-    #------------------------------------------------------------------------------
-    def cast_with_mongoid(object, type)
-      cast = cast_without_mongoid(object, type)
-      if defined?(::Mongoid::Document)
-        if object.is_a?(Class) && object.ancestors.include?(::Mongoid::Document)
-          cast = :mongoid_class
-        elsif object.class.ancestors.include?(::Mongoid::Document)
-          cast = :mongoid_document
-        elsif (defined?(::BSON) && object.is_a?(::BSON::ObjectId)) || (defined?(::Moped::BSON) && object.is_a?(::Moped::BSON::ObjectId))
-          cast = :mongoid_bson_id
-        end
-      end
-      cast
-    end
-
-    # Format Mongoid class object.
-    #------------------------------------------------------------------------------
-    def awesome_mongoid_class(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:fields)
-
-      data = object.fields.sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
-        hash[c[1].name.to_sym] = (c[1].type || 'undefined').to_s.underscore.intern
-        hash
-      end
-
-      name = "class #{awesome_simple(object.to_s, :class)}"
-      base = "< #{awesome_simple(object.superclass.to_s, :class)}"
-
-      [name, base, awesome_hash(data)].join(' ')
-    end
-
-    # Format Mongoid Document object.
-    #------------------------------------------------------------------------------
-    def awesome_mongoid_document(object)
-      return object.inspect if !defined?(::ActiveSupport::OrderedHash)
-
-      data = (object.attributes || {}).sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
-        hash[c[0].to_sym] = c[1]
-        hash
-      end
-      data = { errors: object.errors, attributes: data } if !object.errors.empty?
-      "#{object} #{awesome_hash(data)}"
-    end
-
-    # Format BSON::ObjectId
-    #------------------------------------------------------------------------------
-    def awesome_mongoid_bson_id(object)
-      object.inspect
-    end
-  end
-end
-
-AwesomePrint::Formatter.send(:include, AwesomePrint::Mongoid)
diff --git a/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb b/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb
new file mode 100644
index 00000000..af397496
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb
@@ -0,0 +1,56 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class MongoidDocument < BaseFormatter
+
+      formatter_for :mongoid_document
+
+      def self.formattable?(object)
+        defined?(::Mongoid::Document) &&
+          object.class.ancestors.include?(::Mongoid::Document)
+      end
+
+      def format(object)
+        unless defined?(::ActiveSupport::OrderedHash)
+          return Formatters::SimpleFormatter.new(@inspector).format(object.inspect)
+        end
+
+        if object.respond_to?(:fields)
+          # mongoid class
+          format_as_class(object)
+        else
+          format_as_instance(object)
+        end
+      end
+
+    end
+
+    private
+
+    def format_as_class(object)
+      data = object.fields.sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
+        hash[c[1].name.to_sym] = (c[1].type || 'undefined').to_s.underscore.to_sym
+        hash
+      end
+
+      [
+        "class #{colorize(object.to_s, :class)}",
+        "< #{colorize(object.superclass.to_s, :class)}",
+        Formatters::HashFormatter.new(@inspector).format(data)
+      ].join(' ')
+    end
+
+    def format_as_instance(object)
+      data = (object.attributes || {}).sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
+        hash[c[0].to_sym] = c[1]
+        hash
+      end
+
+      data = { errors: object.errors, attributes: data } if !object.errors.empty?
+
+      "#{object} #{Formatters::HashFormatter.new(@inspector).format(data)}"
+    end
+  end
+end
+
diff --git a/lib/awesome_print/formatters/ext/nokogiri.rb b/lib/awesome_print/formatters/ext/nokogiri.rb
deleted file mode 100644
index 1cb385f9..00000000
--- a/lib/awesome_print/formatters/ext/nokogiri.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-module AwesomePrint
-  module Nokogiri
-
-    def self.included(base)
-      base.send :alias_method, :cast_without_nokogiri, :cast
-      base.send :alias_method, :cast, :cast_with_nokogiri
-    end
-
-    # Add Nokogiri XML Node and NodeSet names to the dispatcher pipeline.
-    #------------------------------------------------------------------------------
-    def cast_with_nokogiri(object, type)
-      cast = cast_without_nokogiri(object, type)
-      if (defined?(::Nokogiri::XML::Node) && object.is_a?(::Nokogiri::XML::Node)) ||
-         (defined?(::Nokogiri::XML::NodeSet) && object.is_a?(::Nokogiri::XML::NodeSet))
-        cast = :nokogiri_xml_node
-      end
-      cast
-    end
-
-    #------------------------------------------------------------------------------
-    def awesome_nokogiri_xml_node(object)
-      if object.is_a?(::Nokogiri::XML::NodeSet) && object.empty?
-        return '[]'
-      end
-      xml = object.to_xml(indent: 2)
-      #
-      # Colorize tag, id/class name, and contents.
-      #
-      xml.gsub!(/(<)(\/?[A-Za-z1-9]+)/) { |tag| "#{$1}#{colorize($2, :keyword)}" }
-      xml.gsub!(/(id|class)="[^"]+"/i) { |id| colorize(id, :class) }
-      xml.gsub!(/>([^<]+)#{contents}<"
-      end
-      xml
-    end
-  end
-end
-
-AwesomePrint::Formatter.send(:include, AwesomePrint::Nokogiri)
diff --git a/lib/awesome_print/formatters/ext/nokogiri_node_formatter.rb b/lib/awesome_print/formatters/ext/nokogiri_node_formatter.rb
new file mode 100644
index 00000000..d6f6ed0f
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/nokogiri_node_formatter.rb
@@ -0,0 +1,29 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class NokogiriNodeFormatter < BaseFormatter
+
+      formatter_for :nokogiri_xml_node
+
+      def self.formattable?(object)
+        defined?(::Nokogiri) && object.is_a?(::Nokogiri::XML::Node)
+      end
+
+      def format(object)
+        xml = object.to_xml(indent: 2)
+        #
+        # Colorize tag, id/class name, and contents.
+        #
+        xml.gsub!(/(<)(\/?[A-Za-z1-9]+)/) { |tag| "#{$1}#{colorize($2, :keyword)}" }
+        xml.gsub!(/(id|class)="[^"]+"/i) { |id| colorize(id, :class) }
+        xml.gsub!(/>([^<]+)#{contents}<"
+        end
+        xml
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb b/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb
new file mode 100644
index 00000000..6dc39662
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb
@@ -0,0 +1,32 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class NokogiriNodeFormatter < BaseFormatter
+
+      formatter_for :nokogiri_xml_nodeset
+
+      def self.formattable?(object)
+        defined?(::Nokogiri) && object.is_a?(::Nokogiri::XML::NodeSet)
+      end
+
+      def format(object)
+
+        return '[]' if object.empty?
+
+        xml = object.to_xml(indent: 2)
+        #
+        # Colorize tag, id/class name, and contents.
+        #
+        xml.gsub!(/(<)(\/?[A-Za-z1-9]+)/) { |tag| "#{$1}#{colorize($2, :keyword)}" }
+        xml.gsub!(/(id|class)="[^"]+"/i) { |id| colorize(id, :class) }
+        xml.gsub!(/>([^<]+)#{contents}<"
+        end
+        xml
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/sequel.rb b/lib/awesome_print/formatters/ext/sequel.rb
deleted file mode 100644
index d1248659..00000000
--- a/lib/awesome_print/formatters/ext/sequel.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-module AwesomePrint
-  module Sequel
-
-    def self.included(base)
-      base.send :alias_method, :cast_without_sequel, :cast
-      base.send :alias_method, :cast, :cast_with_sequel
-    end
-
-    # Add Sequel class names to the dispatcher pipeline.
-    #------------------------------------------------------------------------------
-    def cast_with_sequel(object, type)
-      cast = cast_without_sequel(object, type)
-      if defined?(::Sequel::Model) && object.is_a?(::Sequel::Model)
-        cast = :sequel_document
-      elsif defined?(::Sequel::Model) && object.is_a?(Class) && object.ancestors.include?(::Sequel::Model)
-        cast = :sequel_model_class
-      elsif defined?(::Sequel::Mysql2::Dataset) && object.class.ancestors.include?(::Sequel::Mysql2::Dataset)
-        cast = :sequel_dataset
-      end
-      cast
-    end
-
-    # Format Sequel Document object.
-    #------------------------------------------------------------------------------
-    def awesome_sequel_document(object)
-      data = object.values.sort_by { |key| key.to_s }.inject({}) do |hash, c|
-        hash[c[0].to_sym] = c[1]
-        hash
-      end
-      data = { errors: object.errors, values: data } if !object.errors.empty?
-      "#{object} #{awesome_hash(data)}"
-    end
-
-    # Format Sequel Dataset object.
-    #------------------------------------------------------------------------------
-    def awesome_sequel_dataset(dataset)
-      [awesome_array(dataset.to_a), awesome_print(dataset.sql)].join("\n")
-    end
-
-    # Format Sequel Model class.
-    #------------------------------------------------------------------------------
-    def awesome_sequel_model_class(object)
-      data = object.db_schema.inject({}) { |h, (prop, defn)| h.merge(prop => defn[:db_type]) }
-      name = "class #{awesome_simple(object.to_s, :class)}"
-      base = "< #{awesome_simple(object.superclass.to_s, :class)}"
-
-      [name, base, awesome_hash(data)].join(' ')
-    end
-  end
-
-end
-
-AwesomePrint::Formatter.send(:include, AwesomePrint::Sequel)
diff --git a/lib/awesome_print/formatters/ext/sequel_dataset_formatter.rb b/lib/awesome_print/formatters/ext/sequel_dataset_formatter.rb
new file mode 100644
index 00000000..86998542
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/sequel_dataset_formatter.rb
@@ -0,0 +1,20 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class SequelDatasetFormatter < BaseFormatter
+
+      formatter_for :sequel_dataset
+
+      def self.formattable?(object)
+        defined?(::Sequel::Mysql2::Dataset) && object.class.ancestors.include?(::Sequel::Mysql2::Dataset)
+      end
+
+      def format(object)
+        af = Formatters::ArrayFormatter.new(@inspector)
+        [af.format(dataset.to_a), colorize(dataset.sql, :string)].join("\n")
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/sequel_model_class_formatter.rb b/lib/awesome_print/formatters/ext/sequel_model_class_formatter.rb
new file mode 100644
index 00000000..8d93d7cd
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/sequel_model_class_formatter.rb
@@ -0,0 +1,25 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class SequelModelClassFormatter < BaseFormatter
+
+      formatter_for :sequel_model_class
+
+      def self.formattable?(object)
+        defined?(::Sequel::Model) && object.is_a?(Class) && object.ancestors.include?(::Sequel::Model)
+      end
+
+      def format(object)
+        data = object.db_schema.inject({}) { |h, (prop, defn)| h.merge(prop => defn[:db_type]) }
+
+        [
+          "class #{colorize(object.to_s, :class)}",
+          "< #{colorize(object.superclass.to_s, :class)}",
+          Formatters::HashFormatter.new(@inspector).format(data)
+        ].join(' ')
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/sequel_model_formatter.rb b/lib/awesome_print/formatters/ext/sequel_model_formatter.rb
new file mode 100644
index 00000000..27901673
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/sequel_model_formatter.rb
@@ -0,0 +1,26 @@
+require_relative '../base_formatter'
+
+module AwesomePrint
+  module Formatters
+    class SequelModelFormatter < BaseFormatter
+
+      formatter_for :sequel_model
+
+      def self.formattable?(object)
+        defined?(::Sequel::Model) && object.is_a?(::Sequel::Model)
+      end
+
+      def format(object)
+        data = object.values.sort_by { |key| key.to_s }.inject({}) do |hash, c|
+          hash[c[0].to_sym] = c[1]
+          hash
+        end
+        data = { errors: object.errors, values: data } if !object.errors.empty?
+        hf = Formatters::HashFormatter.new(@inspector)
+
+        "#{colorize(object.to_s, :sequel)} #{hf.format(data)}"
+      end
+
+    end
+  end
+end
diff --git a/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb b/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb
new file mode 100644
index 00000000..52e39eb4
--- /dev/null
+++ b/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb
@@ -0,0 +1,21 @@
+require_relative '../base_formatter'
+require 'date'
+
+module AwesomePrint
+  module Formatters
+    class TimeWithZoneFormatter < BaseFormatter
+
+      formatter_for :time_with_zone
+
+      def self.formattable?(object)
+        (defined?(::ActiveSupport::TimeWithZone) && object.is_a?(::ActiveSupport::TimeWithZone)) ||
+          object.is_a?(::DateTime) || Object.is_a?(::Time)
+      end
+
+      def format(object)
+        colorize(object.inspect, :time)
+      end
+
+    end
+  end
+end
diff --git a/spec/ext/action_view_spec.rb b/spec/ext/action_view_spec.rb
deleted file mode 100644
index c772d814..00000000
--- a/spec/ext/action_view_spec.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe 'AwesomePrint ActionView extensions', skip: -> { !ExtVerifier.has_rails? }.call do
-
-  before do
-    @view = ActionView::Base.new
-  end
-
-  it "uses HTML and adds 'debug_dump' class to plain 
 tag" do
-    markup = rand
-    expect(@view.ap(markup, plain: true)).to eq(%Q|
#{markup}
|) - end - - it "uses HTML and adds 'debug_dump' class to colorized
 tag" do
-    markup = ' &'
-    expect(@view.ap(markup)).to eq('
" &<hello>"
') - end -end diff --git a/spec/ext/active_record_spec.rb b/spec/formatters/ext/active_record_spec.rb similarity index 100% rename from spec/ext/active_record_spec.rb rename to spec/formatters/ext/active_record_spec.rb diff --git a/spec/ext/active_support_spec.rb b/spec/formatters/ext/active_support_spec.rb similarity index 100% rename from spec/ext/active_support_spec.rb rename to spec/formatters/ext/active_support_spec.rb diff --git a/spec/ext/mongo_mapper_spec.rb b/spec/formatters/ext/mongo_mapper_spec.rb similarity index 100% rename from spec/ext/mongo_mapper_spec.rb rename to spec/formatters/ext/mongo_mapper_spec.rb diff --git a/spec/ext/mongoid_spec.rb b/spec/formatters/ext/mongoid_spec.rb similarity index 100% rename from spec/ext/mongoid_spec.rb rename to spec/formatters/ext/mongoid_spec.rb diff --git a/spec/ext/nokogiri_spec.rb b/spec/formatters/ext/nokogiri_spec.rb similarity index 100% rename from spec/ext/nokogiri_spec.rb rename to spec/formatters/ext/nokogiri_spec.rb From 7f7c0bf3701de6ec2ee8915729ec9012230d11b5 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 16:11:07 -0500 Subject: [PATCH 10/25] Fix unbound methods --- lib/awesome_print/formatters/method_formatter.rb | 3 +-- .../formatters/unbound_method_formatter.rb | 15 +++++++++++++++ spec/formatters/methods_spec.rb | 9 ++++----- 3 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 lib/awesome_print/formatters/unbound_method_formatter.rb diff --git a/lib/awesome_print/formatters/method_formatter.rb b/lib/awesome_print/formatters/method_formatter.rb index af0db552..047503a5 100644 --- a/lib/awesome_print/formatters/method_formatter.rb +++ b/lib/awesome_print/formatters/method_formatter.rb @@ -11,8 +11,7 @@ def self.core? end def self.formattable?(object) - puts "formattable? for METHOD..." - true + object.is_a?(Method) end def format(method) diff --git a/lib/awesome_print/formatters/unbound_method_formatter.rb b/lib/awesome_print/formatters/unbound_method_formatter.rb new file mode 100644 index 00000000..05134467 --- /dev/null +++ b/lib/awesome_print/formatters/unbound_method_formatter.rb @@ -0,0 +1,15 @@ +require_relative 'method_formatter' + +module AwesomePrint + module Formatters + class UnboundMethodFormatter < MethodFormatter + + formatter_for :unboundmethod + + def self.formattable?(object) + object.is_a?(UnboundMethod) + end + + end + end +end diff --git a/spec/formatters/methods_spec.rb b/spec/formatters/methods_spec.rb index 222727e8..05a2495e 100644 --- a/spec/formatters/methods_spec.rb +++ b/spec/formatters/methods_spec.rb @@ -62,7 +62,9 @@ method = ''.method(:is_a?) expect(method.ai).to eq("\e[1;33mString (Kernel)\e[0m#\e[0;35mis_a?\e[0m\e[0;37m(arg1)\e[0m") end +end +RSpec.describe 'unbound methods' do it 'plain: should handle an unbound method' do class Hello def world; end @@ -76,11 +78,8 @@ class Hello def world(a, b); end end method = Hello.instance_method(:world) - if RUBY_VERSION < '1.9.2' - expect(method.ai).to eq("\e[1;33mHello (unbound)\e[0m#\e[0;35mworld\e[0m\e[0;37m(arg1, arg2)\e[0m") - else - expect(method.ai).to eq("\e[1;33mHello (unbound)\e[0m#\e[0;35mworld\e[0m\e[0;37m(a, b)\e[0m") - end + puts "\e[1;33mHello (unbound)\e[0m#\e[0;35mworld\e[0m\e[0;37m(a, b)\e[0m" + expect(method.ai).to eq("\e[1;33mHello (unbound)\e[0m#\e[0;35mworld\e[0m\e[0;37m(a, b)\e[0m") end end From bf1ff1368c2564ecaebaa4f26d754e87d4f7d9d8 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 16:34:16 -0500 Subject: [PATCH 11/25] Fix more tests --- lib/ap.rb | 6 ++++++ lib/awesome_print.rb | 6 +++--- lib/awesome_print/formatters/object_formatter.rb | 5 +++++ lib/awesome_print/inspector.rb | 1 + spec/misc_spec.rb | 6 +++--- 5 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 lib/ap.rb diff --git a/lib/ap.rb b/lib/ap.rb new file mode 100644 index 00000000..b8a62617 --- /dev/null +++ b/lib/ap.rb @@ -0,0 +1,6 @@ +# +# Keeping this for backwards compatibility to allow +# require "ap" +# +require File.dirname(__FILE__) + '/awesome_print' + diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index 7200b532..f2ce1479 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -6,12 +6,12 @@ require "awesome_print/core_ext/#{file}" end - require 'awesome_print/version' - require 'awesome_print/core_ext/logger' if defined?(Logger) - require 'awesome_print/custom_defaults' require 'awesome_print/inspector' require 'awesome_print/formatter' Dir["./lib/awesome_print/formatters/**/*.rb"].each { |f| require f } + + require 'awesome_print/version' + require 'awesome_print/core_ext/logger' if defined?(Logger) end diff --git a/lib/awesome_print/formatters/object_formatter.rb b/lib/awesome_print/formatters/object_formatter.rb index 67c2bef8..d6d8a0b2 100644 --- a/lib/awesome_print/formatters/object_formatter.rb +++ b/lib/awesome_print/formatters/object_formatter.rb @@ -20,6 +20,11 @@ def format(object) @object = object @variables = object.instance_variables + # special case for ENV hashes, as they are objects but hash. + if object.to_s == 'ENV' && object.respond_to?(:to_h) + return Formatters::HashFormatter.new(@inspector).format(object.to_h) + end + vars = variables.map do |var| property = var.to_s[1..-1].to_sym # to_s because of some monkey patching done by Puppet. accessor = if object.respond_to?(:"#{property}=") diff --git a/lib/awesome_print/inspector.rb b/lib/awesome_print/inspector.rb index c7aeeeb0..4bc81dc1 100644 --- a/lib/awesome_print/inspector.rb +++ b/lib/awesome_print/inspector.rb @@ -27,6 +27,7 @@ def initialize(options = {}) class: :yellow, date: :greenish, falseclass: :red, + simple: :blue, fixnum: :blue, integer: :blue, float: :blue, diff --git a/spec/misc_spec.rb b/spec/misc_spec.rb index bbada404..5876c1c6 100644 --- a/spec/misc_spec.rb +++ b/spec/misc_spec.rb @@ -18,7 +18,7 @@ def inspect 'ice'.freeze end end - expect(weird.new.ai(plain: false)).to eq('ice') + expect(weird.new.ai(plain: true)).to eq('ice') end # See https://github.com/awesome-print/awesome_print/issues/35 @@ -45,7 +45,7 @@ def inspect # Require different file name this time (lib/ap.rb vs. lib/awesome_print). it "several require 'awesome_print' should do no harm" do - require File.expand_path(File.dirname(__FILE__) + '/../lib/ap') + require File.expand_path(File.dirname(__FILE__) + '/../lib/awesome_print') expect { rand.ai }.not_to raise_error end @@ -58,7 +58,7 @@ def inspect it 'IPAddr workaround' do require 'ipaddr' ipaddr = IPAddr.new('3ffe:505:2::1') - expect(ipaddr.ai).to eq('#') + expect(ipaddr.ai(plain: true)).to eq('#') end # See https://github.com/awesome-print/awesome_print/issues/139 From 1e5c6c92f4edc09fe30c24e20941f255ea6f1c70 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 16:43:22 -0500 Subject: [PATCH 12/25] Fix nokogiri errors --- .../ext/nokogiri_document_formatter.rb | 30 +++++++++++++++++++ .../ext/nokogiri_nodeset_formatter.rb | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 lib/awesome_print/formatters/ext/nokogiri_document_formatter.rb diff --git a/lib/awesome_print/formatters/ext/nokogiri_document_formatter.rb b/lib/awesome_print/formatters/ext/nokogiri_document_formatter.rb new file mode 100644 index 00000000..379a88cb --- /dev/null +++ b/lib/awesome_print/formatters/ext/nokogiri_document_formatter.rb @@ -0,0 +1,30 @@ +require_relative '../base_formatter' + +module AwesomePrint + module Formatters + class NokogiriDocumentFormatter < BaseFormatter + + formatter_for :nokogiri_xml_document + + def self.formattable?(object) + defined?(::Nokogiri) && object.is_a?(::Nokogiri::XML::Document) + end + + def format(object) + + xml = object.to_xml(indent: 2) + # + # Colorize tag, id/class name, and contents. + # + xml.gsub!(/(<)(\/?[A-Za-z1-9]+)/) { |tag| "#{$1}#{colorize($2, :keyword)}" } + xml.gsub!(/(id|class)="[^"]+"/i) { |id| colorize(id, :class) } + xml.gsub!(/>([^<]+)#{contents}<" + end + xml + end + + end + end +end diff --git a/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb b/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb index 6dc39662..d0b6f7a2 100644 --- a/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb +++ b/lib/awesome_print/formatters/ext/nokogiri_nodeset_formatter.rb @@ -2,7 +2,7 @@ module AwesomePrint module Formatters - class NokogiriNodeFormatter < BaseFormatter + class NokogiriNodesetFormatter < BaseFormatter formatter_for :nokogiri_xml_nodeset From 751d6c9fc18e1c3193d76e07411f7dc2056e3a09 Mon Sep 17 00:00:00 2001 From: James Cox Date: Tue, 22 Jan 2019 16:50:04 -0500 Subject: [PATCH 13/25] fix load order... --- lib/awesome_print.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index f2ce1479..02108107 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -2,11 +2,13 @@ # so do nothing for subsequent requires. # unless defined?(AwesomePrint::Inspector) + # FIXME: not sure we need these, but.. + require 'awesome_print/custom_defaults' + %w(active_support awesome_method_array string object class kernel).each do |file| require "awesome_print/core_ext/#{file}" end - require 'awesome_print/custom_defaults' require 'awesome_print/inspector' require 'awesome_print/formatter' From e2acfab48a7fd180a3cdc3f5ffa3bf894bdd3884 Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 11:28:26 -0500 Subject: [PATCH 14/25] Remove extra puts in spec. --- spec/formatters/methods_spec.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/spec/formatters/methods_spec.rb b/spec/formatters/methods_spec.rb index 05a2495e..2b0a025a 100644 --- a/spec/formatters/methods_spec.rb +++ b/spec/formatters/methods_spec.rb @@ -78,7 +78,6 @@ class Hello def world(a, b); end end method = Hello.instance_method(:world) - puts "\e[1;33mHello (unbound)\e[0m#\e[0;35mworld\e[0m\e[0;37m(a, b)\e[0m" expect(method.ai).to eq("\e[1;33mHello (unbound)\e[0m#\e[0;35mworld\e[0m\e[0;37m(a, b)\e[0m") end end From a45b2ac5d702cd6eac204001a14293cf3207d0ed Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 11:45:40 -0500 Subject: [PATCH 15/25] Fix typo, and formally include date as a type here --- .../formatters/ext/time_with_zone_formatter.rb | 2 +- spec/formatters/ext/active_support_spec.rb | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb b/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb index 52e39eb4..fcedf5da 100644 --- a/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb +++ b/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb @@ -9,7 +9,7 @@ class TimeWithZoneFormatter < BaseFormatter def self.formattable?(object) (defined?(::ActiveSupport::TimeWithZone) && object.is_a?(::ActiveSupport::TimeWithZone)) || - object.is_a?(::DateTime) || Object.is_a?(::Time) + object.is_a?(::DateTime) || object.is_a?(::Time) || object.is_a?(::Date) end def format(object) diff --git a/spec/formatters/ext/active_support_spec.rb b/spec/formatters/ext/active_support_spec.rb index f14299d2..e93e5784 100644 --- a/spec/formatters/ext/active_support_spec.rb +++ b/spec/formatters/ext/active_support_spec.rb @@ -10,12 +10,7 @@ time = Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone expect(@ap.send(:awesome, time)).to eq("\e[0;32mSat, 10 Feb 2007 15:30:45 EST -05:00\e[0m") end - - it 'should format HashWithIndifferentAccess as regular Hash' do - hash = HashWithIndifferentAccess.new({ hello: 'world' }) - expect(@ap.send(:awesome, hash)).to eq("{\n \"hello\"\e[0;37m => \e[0m\e[0;33m\"world\"\e[0m\n}") - end - + # # ActiveSupport sticks in instance variables to the date object. Make sure # we ignore that and format Date instance as regular date. it 'should formate Date object as date' do @@ -23,4 +18,9 @@ expect(date.ai(plain: true)).to eq('Mon, 26 May 2003') expect(date.ai).to eq("\e[0;32mMon, 26 May 2003\e[0m") end + + it 'should format HashWithIndifferentAccess as regular Hash' do + hash = HashWithIndifferentAccess.new({ hello: 'world' }) + expect(@ap.send(:awesome, hash)).to eq("{\n \"hello\"\e[0;37m => \e[0m\e[0;33m\"world\"\e[0m\n}") + end end From 5eb57ad5553bd6da7c08b725d344fa1a7078493a Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 14:17:07 -0500 Subject: [PATCH 16/25] Remove no longer required active record stubs --- spec/support/active_record_data/3_2_diana.txt | 24 -- .../active_record_data/3_2_diana_legacy.txt | 24 -- spec/support/active_record_data/3_2_multi.txt | 50 ---- .../active_record_data/3_2_multi_legacy.txt | 50 ---- spec/support/active_record_data/4_0_diana.txt | 98 -------- spec/support/active_record_data/4_0_multi.txt | 198 ---------------- spec/support/active_record_data/4_1_diana.txt | 97 -------- spec/support/active_record_data/4_1_multi.txt | 196 ---------------- spec/support/active_record_data/4_2_diana.txt | 109 --------- .../active_record_data/4_2_diana_legacy.txt | 109 --------- spec/support/active_record_data/4_2_multi.txt | 220 ------------------ .../active_record_data/4_2_multi_legacy.txt | 220 ------------------ spec/support/rails_versions.rb | 22 +- 13 files changed, 1 insertion(+), 1416 deletions(-) delete mode 100644 spec/support/active_record_data/3_2_diana.txt delete mode 100644 spec/support/active_record_data/3_2_diana_legacy.txt delete mode 100644 spec/support/active_record_data/3_2_multi.txt delete mode 100644 spec/support/active_record_data/3_2_multi_legacy.txt delete mode 100644 spec/support/active_record_data/4_0_diana.txt delete mode 100644 spec/support/active_record_data/4_0_multi.txt delete mode 100644 spec/support/active_record_data/4_1_diana.txt delete mode 100644 spec/support/active_record_data/4_1_multi.txt delete mode 100644 spec/support/active_record_data/4_2_diana.txt delete mode 100644 spec/support/active_record_data/4_2_diana_legacy.txt delete mode 100644 spec/support/active_record_data/4_2_multi.txt delete mode 100644 spec/support/active_record_data/4_2_multi_legacy.txt diff --git a/spec/support/active_record_data/3_2_diana.txt b/spec/support/active_record_data/3_2_diana.txt deleted file mode 100644 index 0eb543f5..00000000 --- a/spec/support/active_record_data/3_2_diana.txt +++ /dev/null @@ -1,24 +0,0 @@ -# false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } -> diff --git a/spec/support/active_record_data/3_2_diana_legacy.txt b/spec/support/active_record_data/3_2_diana_legacy.txt deleted file mode 100644 index 266ad53b..00000000 --- a/spec/support/active_record_data/3_2_diana_legacy.txt +++ /dev/null @@ -1,24 +0,0 @@ -# false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - }, - attr_reader :mass_assignment_options = nil -> diff --git a/spec/support/active_record_data/3_2_multi.txt b/spec/support/active_record_data/3_2_multi.txt deleted file mode 100644 index e16765d0..00000000 --- a/spec/support/active_record_data/3_2_multi.txt +++ /dev/null @@ -1,50 +0,0 @@ -[ - [0] # false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - >, - [1] # true, - "created_at" => "2003-05-26 14:15:00", - "id" => nil, - "name" => "Laura", - "rank" => 2 - }, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - > -] diff --git a/spec/support/active_record_data/3_2_multi_legacy.txt b/spec/support/active_record_data/3_2_multi_legacy.txt deleted file mode 100644 index d5f840af..00000000 --- a/spec/support/active_record_data/3_2_multi_legacy.txt +++ /dev/null @@ -1,50 +0,0 @@ -[ - [0] # false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - }, - attr_reader :mass_assignment_options = nil - >, - [1] # true, - "created_at" => "2003-05-26 14:15:00", - "id" => nil, - "name" => "Laura", - "rank" => 2 - }, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - }, - attr_reader :mass_assignment_options = nil - > -] diff --git a/spec/support/active_record_data/4_0_diana.txt b/spec/support/active_record_data/4_0_diana.txt deleted file mode 100644 index a9dbd42e..00000000 --- a/spec/support/active_record_data/4_0_diana.txt +++ /dev/null @@ -1,98 +0,0 @@ -# #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @column_types_override = nil, - @destroyed = false, - @marked_for_destruction = false, - @new_record = true, - @previously_changed = {}, - @readonly = false, - @reflects_state = [ - [0] false - ], - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = { - "admin" => false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } -> diff --git a/spec/support/active_record_data/4_0_multi.txt b/spec/support/active_record_data/4_0_multi.txt deleted file mode 100644 index 280b04cf..00000000 --- a/spec/support/active_record_data/4_0_multi.txt +++ /dev/null @@ -1,198 +0,0 @@ -[ - [0] # #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @column_types_override = nil, - @destroyed = false, - @marked_for_destruction = false, - @new_record = true, - @previously_changed = {}, - @readonly = false, - @reflects_state = [ - [0] false - ], - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = { - "admin" => false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - >, - [1] # #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @column_types_override = nil, - @destroyed = false, - @marked_for_destruction = false, - @new_record = true, - @previously_changed = {}, - @readonly = false, - @reflects_state = [ - [0] false - ], - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = { - "admin" => true, - "created_at" => "2003-05-26 14:15:00", - "id" => nil, - "name" => "Laura", - "rank" => 2 - }, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - > -] diff --git a/spec/support/active_record_data/4_1_diana.txt b/spec/support/active_record_data/4_1_diana.txt deleted file mode 100644 index 3ea30daa..00000000 --- a/spec/support/active_record_data/4_1_diana.txt +++ /dev/null @@ -1,97 +0,0 @@ -# #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @column_types_override = nil, - @destroyed = false, - @marked_for_destruction = false, - @new_record = true, - @readonly = false, - @reflects_state = [ - [0] false - ], - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = { - "admin" => false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } -> diff --git a/spec/support/active_record_data/4_1_multi.txt b/spec/support/active_record_data/4_1_multi.txt deleted file mode 100644 index 2256cb8f..00000000 --- a/spec/support/active_record_data/4_1_multi.txt +++ /dev/null @@ -1,196 +0,0 @@ -[ - [0] # #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @column_types_override = nil, - @destroyed = false, - @marked_for_destruction = false, - @new_record = true, - @readonly = false, - @reflects_state = [ - [0] false - ], - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = { - "admin" => false, - "created_at" => "1992-10-10 12:30:00", - "id" => nil, - "name" => "Diana", - "rank" => 1 - }, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - >, - [1] # #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @column_types_override = nil, - @destroyed = false, - @marked_for_destruction = false, - @new_record = true, - @readonly = false, - @reflects_state = [ - [0] false - ], - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = { - "admin" => true, - "created_at" => "2003-05-26 14:15:00", - "id" => nil, - "name" => "Laura", - "rank" => 2 - }, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - > -] diff --git a/spec/support/active_record_data/4_2_diana.txt b/spec/support/active_record_data/4_2_diana.txt deleted file mode 100644 index 3f4c46cd..00000000 --- a/spec/support/active_record_data/4_2_diana.txt +++ /dev/null @@ -1,109 +0,0 @@ -# false, - "created_at" => 1992-10-10 12:30:00 UTC, - "name" => "Diana", - "rank" => 1 - }, - @readonly = false, - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = # #, - attr_reader :value = false, - attr_reader :value_before_type_cast = false - >, - "created_at" => #, - attr_reader :value = 1992-10-10 12:30:00 UTC, - attr_reader :value_before_type_cast = "1992-10-10 12:30:00" - >, - "name" => #, - attr_reader :value = "Diana", - attr_reader :value_before_type_cast = "Diana" - >, - "rank" => #, - attr_reader :value = 1, - attr_reader :value_before_type_cast = 1 - > - }, - @materialized = false, - @types = { - "admin" => #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @values = { - "admin" => nil, - "created_at" => nil, - "id" => nil, - "name" => nil, - "rank" => nil - } - > - >, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } -> diff --git a/spec/support/active_record_data/4_2_diana_legacy.txt b/spec/support/active_record_data/4_2_diana_legacy.txt deleted file mode 100644 index 103568db..00000000 --- a/spec/support/active_record_data/4_2_diana_legacy.txt +++ /dev/null @@ -1,109 +0,0 @@ -# false, - "created_at" => 1992-10-10 12:30:00 UTC, - "name" => "Diana", - "rank" => 1 - }, - @readonly = false, - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = # #, - attr_reader :value = false, - attr_reader :value_before_type_cast = false - >, - "created_at" => #, - attr_reader :value = 1992-10-10 12:30:00 UTC, - attr_reader :value_before_type_cast = "1992-10-10 12:30:00" - >, - "name" => #, - attr_reader :value = "Diana", - attr_reader :value_before_type_cast = "Diana" - >, - "rank" => #, - attr_reader :value = 1, - attr_reader :value_before_type_cast = 1 - > - }, - attr_reader :types = { - "admin" => #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - attr_reader :values = { - "admin" => nil, - "created_at" => nil, - "id" => nil, - "name" => nil, - "rank" => nil - } - > - >, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } -> diff --git a/spec/support/active_record_data/4_2_multi.txt b/spec/support/active_record_data/4_2_multi.txt deleted file mode 100644 index 689a0c6a..00000000 --- a/spec/support/active_record_data/4_2_multi.txt +++ /dev/null @@ -1,220 +0,0 @@ -[ - [0] # false, - "created_at" => 1992-10-10 12:30:00 UTC, - "name" => "Diana", - "rank" => 1 - }, - @readonly = false, - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = # #, - attr_reader :value = false, - attr_reader :value_before_type_cast = false - >, - "created_at" => #, - attr_reader :value = 1992-10-10 12:30:00 UTC, - attr_reader :value_before_type_cast = "1992-10-10 12:30:00" - >, - "name" => #, - attr_reader :value = "Diana", - attr_reader :value_before_type_cast = "Diana" - >, - "rank" => #, - attr_reader :value = 1, - attr_reader :value_before_type_cast = 1 - > - }, - @materialized = false, - @types = { - "admin" => #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @values = { - "admin" => nil, - "created_at" => nil, - "id" => nil, - "name" => nil, - "rank" => nil - } - > - >, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - >, - [1] # true, - "created_at" => 2003-05-26 14:15:00 UTC, - "name" => "Laura", - "rank" => 2 - }, - @readonly = false, - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = # #, - attr_reader :value = true, - attr_reader :value_before_type_cast = true - >, - "created_at" => #, - attr_reader :value = 2003-05-26 14:15:00 UTC, - attr_reader :value_before_type_cast = "2003-05-26 14:15:00" - >, - "name" => #, - attr_reader :value = "Laura", - attr_reader :value_before_type_cast = "Laura" - >, - "rank" => #, - attr_reader :value = 2, - attr_reader :value_before_type_cast = 2 - > - }, - @materialized = false, - @types = { - "admin" => #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - @values = { - "admin" => nil, - "created_at" => nil, - "id" => nil, - "name" => nil, - "rank" => nil - } - > - >, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - > -] diff --git a/spec/support/active_record_data/4_2_multi_legacy.txt b/spec/support/active_record_data/4_2_multi_legacy.txt deleted file mode 100644 index c826ff7d..00000000 --- a/spec/support/active_record_data/4_2_multi_legacy.txt +++ /dev/null @@ -1,220 +0,0 @@ -[ - [0] # false, - "created_at" => 1992-10-10 12:30:00 UTC, - "name" => "Diana", - "rank" => 1 - }, - @readonly = false, - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = # #, - attr_reader :value = false, - attr_reader :value_before_type_cast = false - >, - "created_at" => #, - attr_reader :value = 1992-10-10 12:30:00 UTC, - attr_reader :value_before_type_cast = "1992-10-10 12:30:00" - >, - "name" => #, - attr_reader :value = "Diana", - attr_reader :value_before_type_cast = "Diana" - >, - "rank" => #, - attr_reader :value = 1, - attr_reader :value_before_type_cast = 1 - > - }, - attr_reader :types = { - "admin" => #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - attr_reader :values = { - "admin" => nil, - "created_at" => nil, - "id" => nil, - "name" => nil, - "rank" => nil - } - > - >, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - >, - [1] # true, - "created_at" => 2003-05-26 14:15:00 UTC, - "name" => "Laura", - "rank" => 2 - }, - @readonly = false, - @transaction_state = nil, - @txn = nil, - attr_accessor :attributes = # #, - attr_reader :value = true, - attr_reader :value_before_type_cast = true - >, - "created_at" => #, - attr_reader :value = 2003-05-26 14:15:00 UTC, - attr_reader :value_before_type_cast = "2003-05-26 14:15:00" - >, - "name" => #, - attr_reader :value = "Laura", - attr_reader :value_before_type_cast = "Laura" - >, - "rank" => #, - attr_reader :value = 2, - attr_reader :value_before_type_cast = 2 - > - }, - attr_reader :types = { - "admin" => #, - "created_at" => #, - "id" => #, - "name" => #, - "rank" => # - }, - attr_reader :values = { - "admin" => nil, - "created_at" => nil, - "id" => nil, - "name" => nil, - "rank" => nil - } - > - >, - attr_accessor :destroyed_by_association = nil, - attr_reader :association_cache = {}, - attr_reader :changed_attributes = { - "admin" => nil, - "created_at" => nil, - "name" => nil, - "rank" => nil - } - > -] diff --git a/spec/support/rails_versions.rb b/spec/support/rails_versions.rb index e6c6d1f7..c75a5916 100644 --- a/spec/support/rails_versions.rb +++ b/spec/support/rails_versions.rb @@ -14,29 +14,9 @@ def rails_5_1? alias_method :activerecord_5_1?, :rails_5_1? def rails_5_0? - Gem::Requirement.new('~> 5.0.0.racecar1').satisfied_by?(rails_version) + Gem::Requirement.new('~> 5.0.0').satisfied_by?(rails_version) end alias_method :activerecord_5_0?, :rails_5_0? - - def rails_4_2? - Gem::Requirement.new('~> 4.2.0').satisfied_by?(rails_version) - end - alias_method :activerecord_4_2?, :rails_4_2? - - def rails_4_1? - Gem::Requirement.new('~> 4.1.0').satisfied_by?(rails_version) - end - alias_method :activerecord_4_1?, :rails_4_1? - - def rails_4_0? - Gem::Requirement.new('~> 4.0.0').satisfied_by?(rails_version) - end - alias_method :activerecord_4_0?, :rails_4_0? - - def rails_3_2? - Gem::Requirement.new('~> 3.2.0').satisfied_by?(rails_version) - end - alias_method :activerecord_3_2?, :rails_3_2? end RSpec.configure do |config| From dbe414d4c8e9e29e5fa07e8f1162ad8945d8f350 Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 14:17:41 -0500 Subject: [PATCH 17/25] make debug reporting clearer, though this needs extracting --- lib/awesome_print/colorize.rb | 2 +- lib/awesome_print/formatter.rb | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/awesome_print/colorize.rb b/lib/awesome_print/colorize.rb index 0d0742dd..b8b04f33 100644 --- a/lib/awesome_print/colorize.rb +++ b/lib/awesome_print/colorize.rb @@ -6,7 +6,7 @@ module Colorize # Pick the color and apply it to the given string as necessary. #------------------------------------------------------------------------------ def colorize(str, type) - puts "[COLORIZING] - using #{options[:color][type]} for #{type}" if AwesomePrint.debug + # puts "[COLORIZING] - using #{options[:color][type]} for #{type}" if AwesomePrint.debug str = CGI.escapeHTML(str) if options[:html] if options[:plain] || !options[:color][type] || !inspector.colorize? diff --git a/lib/awesome_print/formatter.rb b/lib/awesome_print/formatter.rb index c5c996b6..f496338d 100644 --- a/lib/awesome_print/formatter.rb +++ b/lib/awesome_print/formatter.rb @@ -31,10 +31,10 @@ def initialize(inspector) # type is determined by Inspector#printable #------------------------------------------------------------------------------ def format(object, type = nil) - puts "[FORMAT] #{type.to_s.red} >>> #{object}" if AwesomePrint.debug + puts "\n\n[FMT] #{type.to_s.red} >>> #{object}" if AwesomePrint.debug format_with = active_formatter(type) - puts "[ACTIVE] using > #{format_with.to_s.blueish} < to format" if AwesomePrint.debug + puts "[ACTIVE] using > #{format_with.to_s.blueish} < to format" if format_with && AwesomePrint.debug # if we have an active formatter, and it's good to go, lets return that @@ -42,10 +42,14 @@ def format(object, type = nil) # if that's not working, lets try discover the format via formattable? self.class.registered_formatters.each do |fmt| - puts "[FORMATTABLE] trying to use #{fmt} - #{fmt.last.core?}" if AwesomePrint.debug + puts "[FIND] trying to use [#{fmt.first.to_s.greenish} - #{fmt.last.to_s.blue}] - core: #{fmt.last.core?}" if AwesomePrint.debug + #{fmt.last.core?}" if AwesomePrint.debug next if fmt.last.core? # if it's a core level formatter, move on - return fmt.last.new(@inspector).format(object) if fmt.last.formattable?(object) + if fmt.last.formattable?(object) + puts "[FMT] Jackpot! using #{fmt.first.to_s.red} >>> #{object}" if AwesomePrint.debug + return fmt.last.new(@inspector).format(object) + end end # we've run out of options. lets try and coerce into something we can work From 7ace70b774c1fe6db4836a542871cdf0ee49bcab Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 14:18:45 -0500 Subject: [PATCH 18/25] Include other obvious formatters --- .../active_record_attributeset_formatter.rb | 25 +++++++++++++++++++ .../ext/active_record_class_formatter.rb | 10 ++++---- .../ext/time_with_zone_formatter.rb | 3 +++ .../formatters/module_formatter.rb | 18 +++++++++++++ .../formatters/range_formatter.rb | 11 ++++++++ lib/awesome_print/inspector.rb | 2 ++ 6 files changed, 64 insertions(+), 5 deletions(-) create mode 100644 lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb create mode 100644 lib/awesome_print/formatters/module_formatter.rb create mode 100644 lib/awesome_print/formatters/range_formatter.rb diff --git a/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb b/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb new file mode 100644 index 00000000..d586773d --- /dev/null +++ b/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb @@ -0,0 +1,25 @@ +require_relative '../base_formatter' + +module AwesomePrint + module Formatters + class ActiveRecordAttributesetFormatter < BaseFormatter + + formatter_for :active_record_attributeset + + def self.core? + false + end + + def self.formattable?(object) + defined?(::ActiveRecord) && object.is_a?(ActiveRecord::AttributeSet) + end + + def format(object) + # simple formatter for now + Formatters::ObjectFormatter.new(@inspector).format(object) + end + + + end + end +end diff --git a/lib/awesome_print/formatters/ext/active_record_class_formatter.rb b/lib/awesome_print/formatters/ext/active_record_class_formatter.rb index d733b397..2dc26300 100644 --- a/lib/awesome_print/formatters/ext/active_record_class_formatter.rb +++ b/lib/awesome_print/formatters/ext/active_record_class_formatter.rb @@ -4,15 +4,16 @@ module AwesomePrint module Formatters class ActiveRecordClassFormatter < BaseFormatter - formatter_for :active_record_class + formatter_for :activerecord_base_class def self.formattable?(object) - defined?(::ActiveRecord) && - (object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base)) + defined?(::ActiveRecord) && object.is_a?(Class) && + (object.superclass == ::ActiveRecord::Base || + object.ancestors.include?(::ActiveRecord::Base)) end def format(object) - if @options[:raw] + if @options[:raw] || object.to_s == "ActiveRecord::Base" return Formatters::ObjectFormatter.new(@inspector).format(object) end @@ -24,7 +25,6 @@ def format(object) return Formatters::SimpleFormatter.new(@inspector).format(object.inspect) end - data = object.columns.inject(::ActiveSupport::OrderedHash.new) do |hash, c| hash[c.name.to_sym] = c.type hash diff --git a/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb b/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb index fcedf5da..58b42d08 100644 --- a/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb +++ b/lib/awesome_print/formatters/ext/time_with_zone_formatter.rb @@ -7,6 +7,9 @@ class TimeWithZoneFormatter < BaseFormatter formatter_for :time_with_zone + # FIXME: should date/time/datetime not become more formal core formatters + # [maybe with tz info and other more useful things]? + def self.formattable?(object) (defined?(::ActiveSupport::TimeWithZone) && object.is_a?(::ActiveSupport::TimeWithZone)) || object.is_a?(::DateTime) || object.is_a?(::Time) || object.is_a?(::Date) diff --git a/lib/awesome_print/formatters/module_formatter.rb b/lib/awesome_print/formatters/module_formatter.rb new file mode 100644 index 00000000..034bd776 --- /dev/null +++ b/lib/awesome_print/formatters/module_formatter.rb @@ -0,0 +1,18 @@ +require_relative 'base_formatter' + +module AwesomePrint + module Formatters + class ModuleFormatter < BaseFormatter + + formatter_for :module + + def self.formattable?(object) + object.is_a?(Module) + end + + def format(object) + colorize(object.inspect, :module) + end + end + end +end diff --git a/lib/awesome_print/formatters/range_formatter.rb b/lib/awesome_print/formatters/range_formatter.rb new file mode 100644 index 00000000..7fa51f1e --- /dev/null +++ b/lib/awesome_print/formatters/range_formatter.rb @@ -0,0 +1,11 @@ +require_relative 'simple_formatter' + +module AwesomePrint + module Formatters + class RangeFormatter < SimpleFormatter + + formatter_for :range + + end + end +end diff --git a/lib/awesome_print/inspector.rb b/lib/awesome_print/inspector.rb index 4bc81dc1..419ce502 100644 --- a/lib/awesome_print/inspector.rb +++ b/lib/awesome_print/inspector.rb @@ -25,11 +25,13 @@ def initialize(options = {}) array: :white, bigdecimal: :blue, class: :yellow, + module: :green, date: :greenish, falseclass: :red, simple: :blue, fixnum: :blue, integer: :blue, + range: :blue, float: :blue, hash: :pale, keyword: :cyan, From da29f748f2a0ee8bf933eec4254657e041f2af20 Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 14:19:35 -0500 Subject: [PATCH 19/25] hack to support finding AR::B classes sigh. this needs to be done way better. --- lib/awesome_print/inspector.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/awesome_print/inspector.rb b/lib/awesome_print/inspector.rb index 419ce502..d3ed6b22 100644 --- a/lib/awesome_print/inspector.rb +++ b/lib/awesome_print/inspector.rb @@ -123,7 +123,13 @@ def unnested(object) # base class. #--------------------------------------------------------------------------- def printable(object) - object.class.to_s.gsub(/:+/, '_').downcase.to_sym + # FIXME: rails specific hack. this needs to be extracted into a + # awesome_print-rails binding lib or something. + if defined?(::ActiveRecord) && object.respond_to?(:ancestors) && object.ancestors.to_a.include?(::ActiveRecord::Base) + :activerecord_base_class + else + object.class.to_s.gsub(/:+/, '_').downcase.to_sym + end end # Update @options by first merging the :color hash and then the remaining From 52933a1c74d69a043746e60ef615949d01a91f17 Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 14:19:44 -0500 Subject: [PATCH 20/25] remove references to older rubies --- spec/formatters/ext/active_record_spec.rb | 80 ++++------------------- 1 file changed, 13 insertions(+), 67 deletions(-) diff --git a/spec/formatters/ext/active_record_spec.rb b/spec/formatters/ext/active_record_spec.rb index 9d024b79..99399952 100644 --- a/spec/formatters/ext/active_record_spec.rb +++ b/spec/formatters/ext/active_record_spec.rb @@ -21,11 +21,7 @@ :rank => 1 } EOS - if RUBY_VERSION < '1.9' - str.sub!('?', 'Sat Oct 10 12:30:00 UTC 1992') - else - str.sub!('?', '1992-10-10 12:30:00 UTC') - end + str.sub!('?', '1992-10-10 12:30:00 UTC') expect(out).to be_similar_to(str) end @@ -49,13 +45,8 @@ } ] EOS - if RUBY_VERSION < '1.9' - str.sub!('??', 'Sat Oct 10 12:30:00 UTC 1992') - str.sub!('?!', 'Mon May 26 14:15:00 UTC 2003') - else - str.sub!('??', '1992-10-10 12:30:00 UTC') - str.sub!('?!', '2003-05-26 14:15:00 UTC') - end + str.sub!('??', '1992-10-10 12:30:00 UTC') + str.sub!('?!', '2003-05-26 14:15:00 UTC') expect(out).to be_similar_to(str) end @@ -81,13 +72,8 @@ } ] EOS - if RUBY_VERSION < '1.9' - str.sub!('??', 'Sat Oct 10 12:30:00 UTC 1992') - str.sub!('?!', 'Mon May 26 14:15:00 UTC 2003') - else - str.sub!('??', '1992-10-10 12:30:00 UTC') - str.sub!('?!', '2003-05-26 14:15:00 UTC') - end + str.sub!('??', '1992-10-10 12:30:00 UTC') + str.sub!('?!', '2003-05-26 14:15:00 UTC') expect(out).to be_similar_to(str) end end @@ -132,22 +118,6 @@ ActiveRecordData.raw_5_1_diana elsif activerecord_5_0? ActiveRecordData.raw_5_0_diana - elsif activerecord_4_2? - if RUBY_VERSION > '1.9.3' - ActiveRecordData.raw_4_2_diana - else - ActiveRecordData.raw_4_2_diana_legacy - end - elsif activerecord_4_1? - ActiveRecordData.raw_4_1_diana - elsif activerecord_4_0? - ActiveRecordData.raw_4_0_diana - elsif activerecord_3_2? - if RUBY_VERSION > '1.9.3' - ActiveRecordData.raw_3_2_diana - else - ActiveRecordData.raw_3_2_diana_legacy - end end raw_object_string.sub!('?', '1992-10-10 12:30:00') expect(out).to be_similar_to(raw_object_string) @@ -163,25 +133,10 @@ ActiveRecordData.raw_5_1_multi elsif activerecord_5_0? ActiveRecordData.raw_5_0_multi - elsif activerecord_4_2? - if RUBY_VERSION > '1.9.3' - ActiveRecordData.raw_4_2_multi - else - ActiveRecordData.raw_4_2_multi_legacy - end - elsif activerecord_4_1? - ActiveRecordData.raw_4_1_multi - elsif activerecord_4_0? - ActiveRecordData.raw_4_0_multi - elsif activerecord_3_2? - if RUBY_VERSION > '1.9.3' - ActiveRecordData.raw_3_2_multi - else - ActiveRecordData.raw_3_2_multi_legacy - end end raw_object_string.sub!('?', '1992-10-10 12:30:00') raw_object_string.sub!('?', '2003-05-26 14:15:00') + expect(out).to be_similar_to(raw_object_string) end end @@ -232,20 +187,15 @@ class SubUser < User { # spec 1 out = @ap.awesome(User.methods.grep(/first/)) - if ActiveRecord::VERSION::STRING >= '3.2' - if RUBY_VERSION >= '2.4.4' - expect(out).to match(/\sfirst\(\*arg.*?\)\s+User/) - elsif RUBY_VERSION >= '1.9' - expect(out).to match(/\sfirst\(\*args,\s&block\)\s+Class \(ActiveRecord::Querying\)/) - else - expect(out).to match(/\sfirst\(\*arg1\)\s+Class \(ActiveRecord::Querying\)/) - end + if RUBY_VERSION >= '2.4.4' + expect(out).to match(/\sfirst\(\*arg.*?\)\s+User/) else - expect(out).to match(/\sfirst\(\*arg.*?\)\s+User \(ActiveRecord::Base\)/) + expect(out).to match(/\sfirst\(\*args,\s&block\)\s+Class \(ActiveRecord::Querying\)/) end # spec 2 out = @ap.awesome(User.methods.grep(/primary_key/)) + if RUBY_VERSION >= '2.4.4' expect(out).to match(/\sprimary_key\(.*?\)\s+User/) else @@ -255,14 +205,10 @@ class SubUser < User { # spec 3 out = @ap.awesome(User.methods.grep(/validate/)) - if ActiveRecord::VERSION::MAJOR < 3 - expect(out).to match(/\svalidate\(\*arg.*?\)\s+User \(ActiveRecord::Base\)/) + if RUBY_VERSION >= '2.4.4' + expect(out).to match(/\svalidate\(\*arg.*?\)\s+User/) else - if RUBY_VERSION >= '2.4.4' - expect(out).to match(/\svalidate\(\*arg.*?\)\s+User/) - else - expect(out).to match(/\svalidate\(\*arg.*?\)\s+Class \(ActiveModel::Validations::ClassMethods\)/) - end + expect(out).to match(/\svalidate\(\*arg.*?\)\s+Class \(ActiveModel::Validations::ClassMethods\)/) end end From 1ff12067cbc29a83c3b14856ef54fd6e368edb5c Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 14:58:51 -0500 Subject: [PATCH 21/25] Fix mongoid concerns --- .../active_record_attributeset_formatter.rb | 4 +- .../ext/mongoid_document_formatter.rb | 45 ++++++++++--------- lib/awesome_print/inspector.rb | 2 + lib/awesome_print/version.rb | 2 +- spec/formatters/ext/mongoid_spec.rb | 4 +- 5 files changed, 32 insertions(+), 25 deletions(-) diff --git a/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb b/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb index d586773d..a14b1832 100644 --- a/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb +++ b/lib/awesome_print/formatters/ext/active_record_attributeset_formatter.rb @@ -11,7 +11,9 @@ def self.core? end def self.formattable?(object) - defined?(::ActiveRecord) && object.is_a?(ActiveRecord::AttributeSet) + defined?(::ActiveRecord) && + defined?(::ActiveRecord::AttributeSet) && + object.is_a?(ActiveRecord::AttributeSet) end def format(object) diff --git a/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb b/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb index af397496..72ecc361 100644 --- a/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb +++ b/lib/awesome_print/formatters/ext/mongoid_document_formatter.rb @@ -8,7 +8,8 @@ class MongoidDocument < BaseFormatter def self.formattable?(object) defined?(::Mongoid::Document) && - object.class.ancestors.include?(::Mongoid::Document) + (object.class.ancestors.include?(::Mongoid::Document) || + (object.respond_to?(:ancestors) && object.ancestors.include?(::Mongoid::Document))) end def format(object) @@ -16,40 +17,42 @@ def format(object) return Formatters::SimpleFormatter.new(@inspector).format(object.inspect) end - if object.respond_to?(:fields) + if object.is_a?(Class) + puts "[MGD] formatting #{object} as class..." if AwesomePrint.debug # mongoid class format_as_class(object) else + puts "[MGD] formatting #{object} as instance..." if AwesomePrint.debug format_as_instance(object) end end - end + private - private + def format_as_class(object) + data = object.fields.sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c| + hash[c[1].name.to_sym] = (c[1].type || 'undefined').to_s.underscore.to_sym + hash + end - def format_as_class(object) - data = object.fields.sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c| - hash[c[1].name.to_sym] = (c[1].type || 'undefined').to_s.underscore.to_sym - hash + [ + "class #{colorize(object.to_s, :class)}", + "< #{colorize(object.superclass.to_s, :class)}", + Formatters::HashFormatter.new(@inspector).format(data) + ].join(' ') end - [ - "class #{colorize(object.to_s, :class)}", - "< #{colorize(object.superclass.to_s, :class)}", - Formatters::HashFormatter.new(@inspector).format(data) - ].join(' ') - end + def format_as_instance(object) + data = (object.attributes || {}).sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c| + hash[c[0].to_sym] = c[1] + hash + end - def format_as_instance(object) - data = (object.attributes || {}).sort_by { |key| key }.inject(::ActiveSupport::OrderedHash.new) do |hash, c| - hash[c[0].to_sym] = c[1] - hash - end + data = { errors: object.errors, attributes: data } if !object.errors.empty? - data = { errors: object.errors, attributes: data } if !object.errors.empty? + "#{object} #{Formatters::HashFormatter.new(@inspector).format(data)}" + end - "#{object} #{Formatters::HashFormatter.new(@inspector).format(data)}" end end end diff --git a/lib/awesome_print/inspector.rb b/lib/awesome_print/inspector.rb index d3ed6b22..8ef906df 100644 --- a/lib/awesome_print/inspector.rb +++ b/lib/awesome_print/inspector.rb @@ -127,6 +127,8 @@ def printable(object) # awesome_print-rails binding lib or something. if defined?(::ActiveRecord) && object.respond_to?(:ancestors) && object.ancestors.to_a.include?(::ActiveRecord::Base) :activerecord_base_class + elsif defined?(::Mongoid) && object.respond_to?(:ancestors) && object.ancestors.to_a.include?(::Mongoid::Document) + :mongoid_document else object.class.to_s.gsub(/:+/, '_').downcase.to_sym end diff --git a/lib/awesome_print/version.rb b/lib/awesome_print/version.rb index adb4285f..37c7c1fa 100644 --- a/lib/awesome_print/version.rb +++ b/lib/awesome_print/version.rb @@ -1,7 +1,7 @@ module AwesomePrint def self.debug - false + false #true end def self.version diff --git a/spec/formatters/ext/mongoid_spec.rb b/spec/formatters/ext/mongoid_spec.rb index cb8e7f3a..af4cb6be 100644 --- a/spec/formatters/ext/mongoid_spec.rb +++ b/spec/formatters/ext/mongoid_spec.rb @@ -40,7 +40,7 @@ class MongoUser it 'should print the class' do class_spec = <<-EOS.strip class MongoUser < Object { - :_id => :"bson/object_id", + :_id => :bson/object_id, :first_name => :string, :last_name => :string } @@ -57,7 +57,7 @@ class Chamelion class_spec = <<-EOS.strip class Chamelion < Object { - :_id => :"bson/object_id", + :_id => :bson/object_id, :last_attribute => :object } EOS From fe0786d27cde3db7cdd159a3d513b194eb9c5d5b Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 15:04:12 -0500 Subject: [PATCH 22/25] Remove mongomapper support. it's out of date, and I don't have time to migrate and validate it. Ideally, these 3rd party lib formatters should be added by that lib, rather than awesome_print introspecting into the lib. --- Appraisals | 17 -- .../ext/mongo_mapper_association_formatter.rb | 31 --- .../ext/mongo_mapper_class_formatter.rb | 41 --- .../ext/mongo_mapper_instance_formatter.rb | 67 ----- spec/formatters/ext/mongo_mapper_spec.rb | 261 ------------------ spec/spec_helper.rb | 2 - spec/support/ext_verifier.rb | 15 - spec/support/rails_versions.rb | 2 +- 8 files changed, 1 insertion(+), 435 deletions(-) delete mode 100644 lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb delete mode 100644 lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb delete mode 100644 spec/formatters/ext/mongo_mapper_spec.rb diff --git a/Appraisals b/Appraisals index 82d15ad5..e67c4b00 100644 --- a/Appraisals +++ b/Appraisals @@ -29,20 +29,3 @@ end appraise 'mongoid-6.0' do gem 'mongoid', '~> 6.0.0' end - -# appraise 'mongo_mapper' do -# gem 'mongo_mapper' -# end -# -# appraise 'ripple' do -# gem 'tzinfo' -# gem 'ripple' -# end -# -# appraise 'nobrainer' do -# gem 'nobrainer' -# -# # When activesupport 5 was released, it required ruby 2.2.2 as a minimum. -# # Locking this down to 4.2.6 allows our Ruby 1.9 tests to keep working. -# gem 'activesupport', '4.2.6', :platforms => :ruby_19 -# end diff --git a/lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb b/lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb deleted file mode 100644 index ff0915f0..00000000 --- a/lib/awesome_print/formatters/ext/mongo_mapper_association_formatter.rb +++ /dev/null @@ -1,31 +0,0 @@ -require_relative '../base_formatter' - -module AwesomePrint - module Formatters - class MongoMapperClassFormatter < BaseFormatter - - formatter_for :mongo_mapper_association - - def self.formattable?(object) - defined?(::MongoMapper) && object.is_a?(::MongoMapper::Plugins::Associations::Base) - end - - def format(object) - if @options[:raw] - return Formatters::ObjectFormatter.new(@inspector).format(object) - end - - if !defined?(::ActiveSupport::OrderedHash) - return Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s) - end - - association = object.class.name.split('::').last.titleize.downcase.sub(/ association$/, '') - association = "embeds #{association}" if object.embeddable? - class_name = object.class_name - - "#{colorize(association, :assoc)} #{colorize(class_name, :class)}" - end - - end - end -end diff --git a/lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb b/lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb deleted file mode 100644 index 7e2b3989..00000000 --- a/lib/awesome_print/formatters/ext/mongo_mapper_class_formatter.rb +++ /dev/null @@ -1,41 +0,0 @@ -require_relative '../base_formatter' - -module AwesomePrint - module Formatters - class MongoMapperClassFormatter < BaseFormatter - - formatter_for :mongo_mapper_class - - def self.formattable?(object) - defined?(::MongoMapper) && - object.is_a?(Class) && - (object.ancestors & [::MongoMapper::Document, ::MongoMapper::EmbeddedDocument]).size > 0 - end - - def format(object) - unless defined?(::ActiveSupport::OrderedHash) && object.respond_to?(:keys) - return Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s) - end - - data = object.keys.sort.inject(::ActiveSupport::OrderedHash.new) do |hash, c| - hash[c.first] = (c.last.type || 'undefined').to_s.underscore.to_sym - hash - end - - # Add in associations - if @options[:mongo_mapper][:show_associations] - object.associations.each { |name, assoc| data[name.to_s] = assoc } - end - - sf = Formatters::SimpleFormatter.new(@inspector) - - [ - "class #{sf.format(object.to_s, :class)}", - "< #{sf.format(object.superclass.to_s, :class)}", - Formatters::HashFormatter.new(@inspector).format(data) - ].join(' ') - end - - end - end -end diff --git a/lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb b/lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb deleted file mode 100644 index fc208d27..00000000 --- a/lib/awesome_print/formatters/ext/mongo_mapper_instance_formatter.rb +++ /dev/null @@ -1,67 +0,0 @@ -require_relative '../base_formatter' - -module AwesomePrint - module Formatters - class MongoMapperInstanceFormatter < BaseFormatter - - formatter_for :mongo_mapper_instance - - def self.formattable?(object) - defined?(::MongoMapper) && - (object.is_a?(::MongoMapper::Document) || - object.is_a?(::MongoMapper::EmbeddedDocument)) - end - - def initialize(inspector) - super(inspector) - - @options[:color][:assoc] ||= :greenish - @options[:mongo_mapper] ||= { - show_associations: false, # Display association data for MongoMapper documents and classes. - inline_embedded: false # Display embedded associations inline with MongoMapper documents. - } - end - - # Format MongoMapper instance object. - # - # NOTE: by default only instance attributes (i.e. keys) are shown. To format - # MongoMapper instance as regular object showing its instance variables and - # accessors use :raw => true option: - # - # ap record, :raw => true - # - #------------------------------------------------------------------------------ - def format(object) - if @options[:raw] - return Formatters::ObjectFormatter.new(@inspector).format(object) - end - - if !defined?(::ActiveSupport::OrderedHash) - return Formatters::SimpleFormatter.new(@inspector).format(object.inspect.to_s) - end - - data = object.keys.keys.sort_by { |k| k }.inject(::ActiveSupport::OrderedHash.new) do |hash, name| - hash[name] = object[name] - hash - end - - # Add in associations - if @options[:mongo_mapper][:show_associations] - object.associations.each do |name, assoc| - data[name.to_s] = if @options[:mongo_mapper][:inline_embedded] and assoc.embeddable? - object.send(name) - else - assoc - end - end - end - - label = object.to_s - label = "#{colorize('embedded', :assoc)} #{label}" if object.is_a?(::MongoMapper::EmbeddedDocument) - - "#{label} " << Formatters::HashFormatter.new(@inspector).format(data) - end - - end - end -end diff --git a/spec/formatters/ext/mongo_mapper_spec.rb b/spec/formatters/ext/mongo_mapper_spec.rb deleted file mode 100644 index 55cb4eb8..00000000 --- a/spec/formatters/ext/mongo_mapper_spec.rb +++ /dev/null @@ -1,261 +0,0 @@ -require 'spec_helper' - -RSpec.describe 'AwesomePrint/MongoMapper', skip: -> { !ExtVerifier.has_mongo_mapper? }.call do - if ExtVerifier.has_mongo_mapper? - before :all do - class MongoUser - include MongoMapper::Document - - key :first_name, String - key :last_name, String - end - end - - after :all do - Object.instance_eval { remove_const :MongoUser } - Object.instance_eval { remove_const :Chamelion } - end - end - - before do - @ap = AwesomePrint::Inspector.new(plain: true, sort_keys: true) - end - - describe 'with the raw option set to true' do - # before { @ap.options[:raw] = true } - before { @ap = AwesomePrint::Inspector.new(plain: true, sort_keys: true, raw: true) } - - it 'should print class instance' do - user = MongoUser.new(first_name: 'Al', last_name: 'Capone') - - out = @ap.send(:awesome, user) - out.gsub!(/#\/, 'AWESOME_PRINT_PROC_STUB') - out.gsub!(/BSON::ObjectId\('[\da-f]+?'\)/, "BSON::ObjectId('123456789')") - - str = if MongoMapper::Version >= '0.13' - <<-EOS.strip -# AWESOME_PRINT_PROC_STUB - }, - attr_accessor :type = ObjectId < Object - > - ], - @__mm_keys = { - "_id" => # AWESOME_PRINT_PROC_STUB - }, - attr_accessor :type = ObjectId < Object - >, - "first_name" => #, - "last_name" => # - }, - @__mm_pre_cast = { - "first_name" => "Al", - "last_name" => "Capone" - }, - @_dynamic_attributes = {}, - @_new = true, - attr_accessor :_id = BSON::ObjectId('123456789'), - attr_accessor :attributes = nil, - attr_accessor :first_name = "Al", - attr_accessor :last_name = "Capone", - attr_reader :changed_attributes = { - "first_name" => nil, - "last_name" => nil - } -> - EOS - else - <<-EOS.strip -# nil, - "last_name" => nil - }, - attr_reader :first_name_before_type_cast = "Al", - attr_reader :last_name_before_type_cast = "Capone" -> - EOS - end - expect(out).to be_similar_to(str) - end - - it 'should print the class' do - expect(@ap.send(:awesome, MongoUser)).to eq <<-EOS.strip -class MongoUser < Object { - "_id" => :object_id, - "first_name" => :string, - "last_name" => :string -} - EOS - end - - it 'should print the class when type is undefined' do - class Chamelion - include MongoMapper::Document - key :last_attribute - end - - expect(@ap.send(:awesome, Chamelion)).to eq <<-EOS.strip -class Chamelion < Object { - "_id" => :object_id, - "last_attribute" => :undefined -} - EOS - end - end - - describe 'with associations' do - - if ExtVerifier.has_mongo_mapper? - before :all do - class Child - include MongoMapper::EmbeddedDocument - key :data - end - - class Sibling - include MongoMapper::Document - key :title - end - - class Parent - include MongoMapper::Document - key :name - - one :child - one :sibling - end - end - end - - describe 'with show associations turned off (default)' do - it 'should render the class as normal' do - expect(@ap.send(:awesome, Parent)).to eq <<-EOS.strip -class Parent < Object { - "_id" => :object_id, - "name" => :undefined -} - EOS - end - - it 'should render an instance as normal' do - parent = Parent.new(name: 'test') - out = @ap.send(:awesome, parent) - str = <<-EOS.strip -# { - "_id" => placeholder_bson_id, - "name" => "test" -} - EOS - expect(out).to be_similar_to(str) - end - end - - describe 'with show associations turned on and inline embedded turned off' do - before :each do - @ap = AwesomePrint::Inspector.new(plain: true, mongo_mapper: { show_associations: true }) - end - - it 'should render the class with associations shown' do - expect(@ap.send(:awesome, Parent)).to eq <<-EOS.strip -class Parent < Object { - "_id" => :object_id, - "name" => :undefined, - "child" => embeds one Child, - "sibling" => one Sibling -} - EOS - end - - it 'should render an instance with associations shown' do - parent = Parent.new(name: 'test') - out = @ap.send(:awesome, parent) - str = <<-EOS.strip -# { - "_id" => placeholder_bson_id, - "name" => "test", - "child" => embeds one Child, - "sibling" => one Sibling -} - EOS - expect(out).to be_similar_to(str) - end - end - - describe 'with show associations turned on and inline embedded turned on' do - before :each do - @ap = AwesomePrint::Inspector.new(plain: true, - mongo_mapper: { - show_associations: true, - inline_embedded: true - } - ) - end - - it 'should render an instance with associations shown and embeds there' do - parent = Parent.new(name: 'test', child: Child.new(data: 5)) - out = @ap.send(:awesome, parent) - str = <<-EOS.strip -# { - "_id" => placeholder_bson_id, - "name" => "test", - "child" => embedded # { - "_id" => placeholder_bson_id, - "data" => 5 - }, - "sibling" => one Sibling -} - EOS - expect(out).to be_similar_to(str) - end - end - end -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index e806a030..cd83c535 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -28,8 +28,6 @@ action_view active_support/all mongoid - mongo_mapper - ripple nobrainer ) ) require 'nokogiri' diff --git a/spec/support/ext_verifier.rb b/spec/support/ext_verifier.rb index 36597ca3..adc2237d 100644 --- a/spec/support/ext_verifier.rb +++ b/spec/support/ext_verifier.rb @@ -19,21 +19,6 @@ def has_mongoid? defined?(Mongoid) end module_function :has_mongoid? - - def has_mongo_mapper? - defined?(MongoMapper) - end - module_function :has_mongo_mapper? - - def has_ripple? - defined?(Ripple) - end - module_function :has_ripple? - - def has_nobrainer? - defined?(NoBrainer) - end - module_function :has_nobrainer? end RSpec.configure do |config| diff --git a/spec/support/rails_versions.rb b/spec/support/rails_versions.rb index c75a5916..f1f1172c 100644 --- a/spec/support/rails_versions.rb +++ b/spec/support/rails_versions.rb @@ -1,6 +1,6 @@ module RailsVersions def rails_version - Gem::Version.new(Rails::VERSION::STRING) + Gem::Version.new(::Rails::VERSION::STRING) end def rails_5_2? From 976e4a5c42ae92594479a1495cbf390f8a9eec85 Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 15:10:44 -0500 Subject: [PATCH 23/25] Make this into a 2.0.0-pre gem --- CHANGELOG.md | 6 +++++- awesome_print.gemspec | 3 +-- lib/awesome_print/version.rb | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a684620..31b11a67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ ## master (unreleased) -## 2.0.0 +## 2.0.0-pre + - Massive overhaul in the way formatters work. Now they are registered with a factory pattern, which includes + a simple method to determine if that formatter can handle the content. [@imajes] + - Remove support for mongo mapper, and ruby pre 2.x [@imajes] + - It's probably faster? :) - Fixes spec suite to properly work via travis, gets a clean build [@imajes, others] - Adds support for ActiveModel::Errors [@dshinzie] - [#301] - removes use of `strip_heredoc` from specs as it's a rails dep [@kstephens] - [#303] diff --git a/awesome_print.gemspec b/awesome_print.gemspec index 0ebbef68..6889b388 100644 --- a/awesome_print.gemspec +++ b/awesome_print.gemspec @@ -4,9 +4,8 @@ require 'awesome_print/version' Gem::Specification.new do |s| s.name = 'awesome_print' s.version = AwesomePrint.version - s.authors = 'Michael Dvorkin' + s.authors = 'Michael Dvorkin, James Cox & contributors' s.date = Time.now.strftime('%Y-%m-%d') - s.email = 'mike@dvorkin.net' s.homepage = 'https://github.com/awesome-print/awesome_print' s.summary = 'Pretty print Ruby objects with proper indentation and colors' s.description = 'Great Ruby debugging companion: pretty print Ruby objects to visualize their structure. Supports custom object formatting via plugins' diff --git a/lib/awesome_print/version.rb b/lib/awesome_print/version.rb index 37c7c1fa..dcc24077 100644 --- a/lib/awesome_print/version.rb +++ b/lib/awesome_print/version.rb @@ -5,6 +5,6 @@ def self.debug end def self.version - '1.8.0' + '2.0.0-pre' end end From 87850a2d6a476f62a35005ec3b3e413a797420bb Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 15:40:44 -0500 Subject: [PATCH 24/25] express the version correctly --- lib/awesome_print/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/awesome_print/version.rb b/lib/awesome_print/version.rb index dcc24077..13b6b491 100644 --- a/lib/awesome_print/version.rb +++ b/lib/awesome_print/version.rb @@ -5,6 +5,6 @@ def self.debug end def self.version - '2.0.0-pre' + '2.0.0.pre' end end From 8242bdf84772622506f83f58743d8c9e4298ff68 Mon Sep 17 00:00:00 2001 From: James Cox Date: Wed, 23 Jan 2019 19:11:53 -0500 Subject: [PATCH 25/25] Fix loadpath issues that became apparent outside of the spec suite --- lib/awesome_print.rb | 35 +++++++++++++++++----------- lib/awesome_print/core_ext/logger.rb | 2 +- lib/awesome_print/custom_defaults.rb | 8 ------- lib/awesome_print/formatters.rb | 11 +-------- lib/awesome_print/registrar.rb | 2 ++ lib/awesome_print/version.rb | 2 +- spec/core_ext/logger_spec.rb | 4 ---- spec/spec_helper.rb | 2 ++ 8 files changed, 28 insertions(+), 38 deletions(-) diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index 02108107..c75166d8 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -1,19 +1,26 @@ -# AwesomePrint might be loaded implicitly through ~/.irbrc or ~/.pryrc -# so do nothing for subsequent requires. -# -unless defined?(AwesomePrint::Inspector) - # FIXME: not sure we need these, but.. - require 'awesome_print/custom_defaults' +require 'awesome_print/formatters' +require 'awesome_print/inspector' +require 'awesome_print/formatter' +require 'awesome_print/version' - %w(active_support awesome_method_array string object class kernel).each do |file| - require "awesome_print/core_ext/#{file}" +module AwesomePrint + class << self + attr_accessor :defaults, :force_colors + + # Class accessor to force colorized output (ex. forked subprocess where TERM + # might be dumb). + #--------------------------------------------------------------------------- + def force_colors!(value = true) + @force_colors = value + end end +end - require 'awesome_print/inspector' - require 'awesome_print/formatter' +# CORE EXTENSIONS... now that ap is loaded, inject awesome behavior into ruby +%w(awesome_method_array string object class kernel logger active_support).each do |file| + require "awesome_print/core_ext/#{file}" +end - Dir["./lib/awesome_print/formatters/**/*.rb"].each { |f| require f } +# FIXME: not sure we need these, but.. +require 'awesome_print/custom_defaults' - require 'awesome_print/version' - require 'awesome_print/core_ext/logger' if defined?(Logger) -end diff --git a/lib/awesome_print/core_ext/logger.rb b/lib/awesome_print/core_ext/logger.rb index 05809a1c..5cfd7c86 100644 --- a/lib/awesome_print/core_ext/logger.rb +++ b/lib/awesome_print/core_ext/logger.rb @@ -11,5 +11,5 @@ def ap(object, level = nil) end end -Logger.send(:include, AwesomePrint::Logger) +Logger.send(:include, AwesomePrint::Logger) if defined?(Logger) ActiveSupport::BufferedLogger.send(:include, AwesomePrint::Logger) if defined?(ActiveSupport::BufferedLogger) diff --git a/lib/awesome_print/custom_defaults.rb b/lib/awesome_print/custom_defaults.rb index aec402a0..7a2193c0 100644 --- a/lib/awesome_print/custom_defaults.rb +++ b/lib/awesome_print/custom_defaults.rb @@ -1,13 +1,5 @@ module AwesomePrint class << self - attr_accessor :defaults, :force_colors - - # Class accessor to force colorized output (ex. forked subprocess where TERM - # might be dumb). - #--------------------------------------------------------------------------- - def force_colors!(value = true) - @force_colors = value - end def console? boolean(defined?(IRB) || defined?(Pry)) diff --git a/lib/awesome_print/formatters.rb b/lib/awesome_print/formatters.rb index e5499587..84484e19 100644 --- a/lib/awesome_print/formatters.rb +++ b/lib/awesome_print/formatters.rb @@ -1,15 +1,6 @@ module AwesomePrint module Formatters - require 'awesome_print/formatters/object_formatter' - require 'awesome_print/formatters/struct_formatter' - require 'awesome_print/formatters/hash_formatter' - require 'awesome_print/formatters/array_formatter' - require 'awesome_print/formatters/simple_formatter' - require 'awesome_print/formatters/method_formatter' - require 'awesome_print/formatters/class_formatter' - require 'awesome_print/formatters/dir_formatter' - require 'awesome_print/formatters/file_formatter' - require 'awesome_print/colorize' + Dir[File.join(__dir__, 'formatters', '**', '*.rb')].each { |f| require f } end end diff --git a/lib/awesome_print/registrar.rb b/lib/awesome_print/registrar.rb index a63475e4..0edbb65d 100644 --- a/lib/awesome_print/registrar.rb +++ b/lib/awesome_print/registrar.rb @@ -1,3 +1,5 @@ +require_relative 'formatter' + module AwesomePrint module Registrar diff --git a/lib/awesome_print/version.rb b/lib/awesome_print/version.rb index 13b6b491..7ce974bf 100644 --- a/lib/awesome_print/version.rb +++ b/lib/awesome_print/version.rb @@ -5,6 +5,6 @@ def self.debug end def self.version - '2.0.0.pre' + '2.0.0.pre2' end end diff --git a/spec/core_ext/logger_spec.rb b/spec/core_ext/logger_spec.rb index ed2d7568..55fc1c9b 100644 --- a/spec/core_ext/logger_spec.rb +++ b/spec/core_ext/logger_spec.rb @@ -1,9 +1,5 @@ require 'spec_helper' - -require 'logger' -require 'awesome_print/core_ext/logger' - RSpec.describe 'AwesomePrint logging extensions' do before(:all) do @logger = Logger.new('/dev/null') rescue Logger.new('nul') diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index cd83c535..33a41a06 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -30,6 +30,8 @@ mongoid ) ) + +require 'logger' require 'nokogiri' require 'awesome_print'