michaeldv/awesome_print — Issue #64: mongoid - support for instances and other issues
Author: gurgeous
Created: 2011-12-13 00:06:50+00:00
State: open

A few suggestions:

1. the mongoid extension needs to handle instances (not just classes)
1. it would be nice to pretty print object ids, otherwise things get really ugly
1. sorted keys are best
1. I prefer symbols (not strings) for keys, but maybe that's personal taste.
1. I'm tormented by issue #61

I tried to fork and create a pull request but I couldn't get the repo to work for some reason. Something to do with the calls to Rake inside the gemspec, which didn't play nicely with Bundler. Sorry about that. Anyway, here's the pertinent code. Thanks again for creating such an awesome gem!

```ruby
# 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 object.is_a?(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[c[1].name] = (c[1].type || "undefined").to_s.underscore.intern rescue c[1].type
hash
end
"class #{object} < #{object.superclass} " << awesome_hash(data)
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
if !object.errors.empty?
data = {:errors => object.errors, :attributes => data}
end
"#{object} #{awesome_hash(data)}"
end

# Format BSON::ObjectId
#------------------------------------------------------------------------------
def awesome_mongoid_bson_id(object)
object.inspect
end
```