Awesome Print通常在Rails中非常适合我。
但是当在Rails控制台中执行ap Post.all
时,我只得到标准的整行输出。
它与返回的ActiveRecord_Relation
类或其他什么有关,因为当返回数组时,就像在ap Post.all.each {|p| p}
中一样,Awesome Print会完成它的工作。
为什么不直接将其转换为数组?
ap Post.all.to_a
或者你可以创建一个补丁:
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
你是对的。也许这是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
当type
是:activerecord_relation
时,该方法将设置转换为数组
而在awsome_print-1.2.0/lib/awsome_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
但是rail4中Relation对象的类类似于:
>Post.all.class
=>ActiveRecord::关系::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
我正在做的是将其放入您的~/.pryrc
中
class Class
def list_all
self.all.each { |s| puts s }
end
end