【问题标题】:Why doesn't Awesome Print work on some Rails collection objects?为什么 Awesome Print 不适用于某些 Rails 集合对象?
【发布时间】:2014-06-10 23:40:12
【问题描述】:

Awesome Print 通常在 Rails 中非常适合我。

但是在 Rails 控制台中执行ap Post.all 时,我只能得到标准的全行输出。

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-console awesomeprint


    【解决方案1】:

    为什么不直接转换成数组呢?

    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 时,该方法将强制转换为数组

    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
    

    【讨论】:

    • 确实如此,但我也很好奇这是否是Relation 类问题(我刚刚猜到是原因),如果是,为什么?
    • 感谢您提供非常有教育意义的答案!
    • 你创建了拉取请求吗?
    • @ArnoldRoa 最新版本的 awesome_print(1.7.0) 已经修复了这个问题。您可以使用bundle update awesome_print进行更新
    【解决方案2】:

    我正在做的是把它放在你的~/.pryrc

    class Class
      def list_all
        self.all.each { |s| puts s }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2020-10-29
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多