【问题标题】:How to show values of a instance with line break in Rails console如何在 Rails 控制台中显示带有换行符的实例的值
【发布时间】:2014-10-22 16:55:22
【问题描述】:

我开始在 Rails 控制台中使用pry。 当我获得 Rails 模型的实例时,显示的值不带换行符,如下所示:

pry(#<Class:0x1022f60e0>):1> first
=> #<Article id: 1, name: "What is Music", content: "Music is an art form in which the medium is sound o...", created_at: "2011-08-24 20:35:29", updated_at: "2011-08-24 20:37:22", published_at: "2011-05-13 23:00:00">

来自http://railscasts.com/episodes/280-pry-with-rails?view=asciicast

有没有办法用这样的换行符显示值?

Article
 id: 1
 name: "What is Music"
 content: "Music is an art form in which the medium is sound o..."
 created_at: "2011-08-24 20:35:29"
 updated_at: "2011-08-24 20:37:22"
 published_at: "2011-05-13 23:00:00"

【问题讨论】:

  • 你试过.to_yaml吗?

标签: ruby-on-rails ruby rails-console pry


【解决方案1】:

您可以在模型实例上调用 .to_yaml!它返回一个字符串,其格式几乎与您要求的完全一样。

以下是 to_yaml 输出的一些示例:

http://yaml4r.sourceforge.net/doc/page/examples.htm

【讨论】:

    【解决方案2】:

    我建议您安装awesome_print

    将其添加到您的Gemfile

    group :development do
      gem 'awesome_print'
    end
    

    并使用bundle install 安装它。

    现在使用ap在控制台打印:

    pry(#<Class:0x1022f60e0>):1> ap first
    
    #<Article:0x1022f60e0> {
               :id => 1,
             :name => "What is Music"
          :content => "Music is an art form in which the medium is sound o..."
       :created_at => "2011-08-24 20:35:29"
       :updated_at => "2011-08-24 20:37:22"
     :published_at => "2011-05-13 23:00:00"
    }
    

    【讨论】:

      【解决方案3】:

      我认为,下面的技巧对你有用。

      arup@linux-wzza:~/Rails/model_prac> rails c
      Loading development environment (Rails 4.1.4)
      2.1.2 :001 > Comment.first
        Comment Load (0.4ms)  SELECT  "comments".* FROM "comments"   ORDER BY "comments"."id" ASC LIMIT 1
       => #<Comment id: 1, value_old: "I am a good Boy.", value_new: "I am a bad Boy.", created_at: "2014-08-02 17:36:14", updated_at: "2014-08-02 18:21:42">
      2.1.2 :002 > y Comment.first
        Comment Load (0.4ms)  SELECT  "comments".* FROM "comments"   ORDER BY "comments"."id" ASC LIMIT 1
      --- !ruby/object:Comment
      attributes:
        id: 1
        value_old: I am a good Boy.
        value_new: I am a bad Boy.
        created_at: 2014-08-02 17:36:14.249466000 Z
        updated_at: 2014-08-02 18:21:42.511522000 Z
       => nil
      2.1.2 :003 >
      

      【讨论】:

        猜你喜欢
        • 2011-02-25
        • 2016-02-07
        • 1970-01-01
        • 2016-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        相关资源
        最近更新 更多