awesome-print / awesome_print

Pretty print your Ruby objects with style -- in full color and with proper indentation
http://github.com/michaeldv/awesome_print
MIT License
4.08k stars 454 forks source link

How to define inspect for a custom class, to make it AP compatible? #107

Closed konung closed 11 years ago

konung commented 11 years ago

Hi

Not a bug, just wondering what does ap expect from MyCustomClass.inspect, in order to get pretty printed output like it does in Rails ?

Right now MyCustomClass.inspect return hash of {:attribute => value}, and that seems to work, but it doesn't look exactly the same. Thanks

michaeldv commented 11 years ago

Check out lib/awesome_print/ext directory for examples on how to do it.

HTH ;-) Michael

benlieb commented 8 years ago

This seemed to work for me:

  def to_hash
    ATTRS.inject({}){|cont, attr| cont[attr] = self.send(attr); cont}
  end

From the AP source: https://github.com/michaeldv/awesome_print/blob/master/lib/awesome_print/formatter.rb

    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