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

Classes that inherit from Array, Hash, File, Dir, and Struct are treated as the base class

This commit is contained in:
Mike Dvorkin 2010-11-06 15:38:53 -07:00
parent c38b70cad4
commit bddee7918e
2 changed files with 70 additions and 7 deletions

View file

@ -6,8 +6,8 @@
require "shellwords"
class AwesomePrint
AP = :__awesome_print__
CORE = [ :array, :hash, :class, :file, :dir, :bigdecimal, :rational, :struct, :method, :unboundmethod ]
AP = :__awesome_print__ unless defined?(AwesomePrint::AP)
CORE = [ :array, :hash, :class, :file, :dir, :bigdecimal, :rational, :struct, :method, :unboundmethod ].freeze unless defined?(AwesomePrint::CORE)
def initialize(options = {})
@options = {
@ -223,13 +223,17 @@ class AwesomePrint
CORE.grep(declassify(object))[0] || :self
end
# Turn class name into symbol, ex: Hello::World => :hello_world.
# Turn class name into symbol, ex: Hello::World => :hello_world. Classes that
# inherit from Array, Hash, File, Dir, and Struct are treated as the base class.
#------------------------------------------------------------------------------
def declassify(object)
if object.is_a?(Struct)
:struct
else
object.class.to_s.gsub(/:+/, "_").downcase.to_sym
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
end

View file

@ -417,4 +417,63 @@ 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 ] ] ])
my.ai(:plain => true).should == <<-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 } } } } } ]
my.ai(:plain => true).should == <<-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')
my.ai(:plain => true).should == "#{my.inspect}\n" << `ls -alF #{my.path}`.chop
end
it "inherited from Dir should be displayed as Dir" do
class My < Dir; end
my = My.new('/tmp')
my.ai(:plain => true).should == "#{my.inspect}\n" << `ls -alF #{my.path}`.chop
end
end
end