module AwesomePrint::ActiveRecord

Public Class Methods

included(base) click to toggle source
# File lib/awesome_print/ext/active_record.rb, line 9
def self.included(base)
  base.send :alias_method, :cast_without_active_record, :cast
  base.send :alias_method, :cast, :cast_with_active_record
end

Public Instance Methods

cast_with_active_record(object, type) click to toggle source

Add ActiveRecord class names to the dispatcher pipeline.

# File lib/awesome_print/ext/active_record.rb, line 16
def cast_with_active_record(object, type)
  cast = cast_without_active_record(object, type)
  return cast if !defined?(::ActiveRecord)

  if object.is_a?(::ActiveRecord::Base)
    cast = :active_record_instance
  elsif object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base)
    cast = :active_record_class
  end
  cast
end

Private Instance Methods

awesome_active_record_class(object) click to toggle source

Format ActiveRecord class object.

# File lib/awesome_print/ext/active_record.rb, line 52
def awesome_active_record_class(object)
  return object.inspect if !defined?(::ActiveSupport::OrderedHash) || !object.respond_to?(:columns) || object.to_s == "ActiveRecord::Base"

  data = object.columns.inject(::ActiveSupport::OrderedHash.new) do |hash, c|
    hash[c.name.to_sym] = c.type
    hash
  end
  "class #{object} < #{object.superclass} " << awesome_hash(data)
end
awesome_active_record_instance(object) click to toggle source

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

# File lib/awesome_print/ext/active_record.rb, line 39
def awesome_active_record_instance(object)
  return object.inspect if !defined?(::ActiveSupport::OrderedHash)
  return awesome_object(object) if @options[:raw]

  data = object.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
    hash[name.to_sym] = object.send(name) if object.has_attribute?(name) || object.new_record?
    hash
  end
  "#{object} " << awesome_hash(data)
end