为什么Awesome Print不能在某些Rails集合对象上工作?

Num*_*ers 5 ruby-on-rails rails-console ruby-on-rails-4 awesomeprint

令人敬畏的打印通常在Rails中完美适用于我.

但是当ap Post.all在Rails控制台中进行操作时,我只获得标准的全线输出.

它与返回的ActiveRecord_Relation类或其他东西有关,因为当返回一个数组时,就像在ap Post.all.each {|p| p},Awesome Print这样做.

D.F*_*Fux 6

为什么不将它转换为数组呢?

ap Post.all.to_a
Run Code Online (Sandbox Code Playgroud)

或者你可以创建一个补丁:

alias :old_ap :ap
def ap(object, option={})
  if object.class == ActiveRecord::Relation::ActiveRecord_Relation_Post
    old_ap object.to_a, option
  else
    old_ap object, option
  end
end
Run Code Online (Sandbox Code Playgroud)


你是对的.也许这是与Rails4不兼容的问题,因为github上的最后一次提交是6个月前.这是问题所在:

awesome_print-1.2.0/lib/awesome_print/ext/active_record.rb@24

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
  elsif type == :activerecord_relation #HERE the problem
    cast = :array
  end
  cast
end
Run Code Online (Sandbox Code Playgroud)

该方法将设置铸造到阵列时type:activerecord_relation

而在awesome_print-1.2.0/lib/awesome_print/inspector.rb@151

def printable(object)
  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 #HERE gets the type
  end
end
Run Code Online (Sandbox Code Playgroud)

但是rails4中的Relation对象类就像:

> Post.all.class
=> ActiveRecord :: Relation :: ActiveRecord_Relation_Post

因此条件cast_with_active_record获取类型"activerecord_relation_activerecord_relation_post"而不是"activerecord_relation".然后条件失败,没有完成转换.

这是一个可能有效的新补丁:

module AwesomePrint
  class Inspector
    alias_method :old_printable, :printable
    private
    def printable(object)
      if object.class.to_s.downcase.include?("activerecord_relation")
        return :activerecord_relation
      end
      old_printable(object)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)