diff --git a/lib/awesome_print.rb b/lib/awesome_print.rb index 3c7c928..e30a2d4 100644 --- a/lib/awesome_print.rb +++ b/lib/awesome_print.rb @@ -36,4 +36,5 @@ unless defined?(AwesomePrint::Inspector) require File.dirname(__FILE__) + "/awesome_print/ext/no_brainer" if defined?(NoBrainer) require File.dirname(__FILE__) + "/awesome_print/ext/ripple" if defined?(Ripple) require File.dirname(__FILE__) + "/awesome_print/ext/sequel" if defined?(Sequel) + require File.dirname(__FILE__) + "/awesome_print/ext/ostruct" if defined?(OpenStruct) end diff --git a/lib/awesome_print/ext/ostruct.rb b/lib/awesome_print/ext/ostruct.rb new file mode 100644 index 0000000..199122f --- /dev/null +++ b/lib/awesome_print/ext/ostruct.rb @@ -0,0 +1,27 @@ +# Copyright (c) 2010-2013 Michael Dvorkin +# +# 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/spec/ext/ostruct_spec.rb b/spec/ext/ostruct_spec.rb new file mode 100644 index 0000000..1071f33 --- /dev/null +++ b/spec/ext/ostruct_spec.rb @@ -0,0 +1,31 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +begin + require 'ostruct' + require 'awesome_print/ext/ostruct' + + describe 'AwesomePrint Ostruct extension' do + before do + stub_dotfile! + @ap = AwesomePrint::Inspector.new(:plain => true, :sort_keys => true) + end + + it "empty hash" do + struct = OpenStruct.new + @ap.send(:awesome, struct).should == "OpenStruct {}" + end + + it "plain multiline" do + struct = OpenStruct.new :name => "Marshall Shen", :address => "605 Madion St." + @ap.send(:awesome, struct).should == <<-EOS.strip +OpenStruct { + :address => "605 Madion St.", + :name => "Marshall Shen" +} +EOS + end + end + +rescue LoadError => error + puts "Skipping OpenStruct specs: #{error}" +end \ No newline at end of file