加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么Awesome Print不适用于某些Rails集合对

发布时间:2020-12-17 03:23:47 所属栏目:百科 来源:网络整理
导读:令人敬畏的打印通常在Rails中完美适用于我. 但是当在Rails控制台中执行ap Post.all时,我只获得标准的全行输出. 是否与返回的ActiveRecord_Relation类或其他内容有关,因为在返回数组时,如在ap Post.all.each中{| p | p},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

当类型为:activerecord_relation时,该方法将cast转换为数组

而在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

但是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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读