Cómo obtener un buen formato en la consola Rails


Quiero que algo como esto se vea bien:

>> ProductColor.all
=> [#<ProductColor id: 1, name: "White", internal_name: "White", created_at: "2009-06-10 04:02:44", updated_at: "2009-06-10 04:02:44">, #<ProductColor id: 2, name: "Ivory", internal_name: "Ivory", created_at: "2009-06-10 04:02:44", updated_at: "2009-06-10 04:02:44">, #<ProductColor id: 3, name: "Blue", internal_name: "Light Blue", created_at: "2009-06-10 04:02:44", updated_at: "2009-06-10 04:02:44">, #<ProductColor id: 4, name: "Green", internal_name: "Green", created_at: "2009-06-10 04:02:44", updated_at: "2009-06-10 04:02:44">]

Esto no funciona:

>> ProductColor.all.inspect
=> "[#<ProductColor id: 1, name: \"White\", internal_name: \"White\", created_at: \"2009-06-10 04:02:44\", updated_at: \"2009-06-10 04:02:44\">, #<ProductColor id: 2, name: \"Ivory\", internal_name: \"Ivory\", created_at: \"2009-06-10 04:02:44\", updated_at: \"2009-06-10 04:02:44\">, #<ProductColor id: 3, name: \"Blue\", internal_name: \"Light Blue\", created_at: \"2009-06-10 04:02:44\", updated_at: \"2009-06-10 04:02:44\">, #<ProductColor id: 4, name: \"Green\", internal_name: \"Green\", created_at: \"2009-06-10 04:02:44\", updated_at: \"2009-06-10 04:02:44\">]"

Y tampoco esto:

>> ProductColor.all.to_yaml
=> "--- \n- !ruby/object:ProductColor \n  attributes: \n    name: White\n    created_at: 2009-06-10 04:02:44\n    updated_at: 2009-06-10 04:02:44\n    id: \"1\"\n    internal_name: White\n  attributes_cache: {}\n\n- !ruby/object:ProductColor \n  attributes: \n    name: Ivory\n    created_at: 2009-06-10 04:02:44\n    updated_at: 2009-06-10 04:02:44\n    id: \"2\"\n    internal_name: Ivory\n  attributes_cache: {}\n\n- !ruby/object:ProductColor \n  attributes: \n    name: Blue\n    created_at: 2009-06-10 04:02:44\n    updated_at: 2009-06-10 04:02:44\n    id: \"3\"\n    internal_name: Light Blue\n  attributes_cache: {}\n\n- !ruby/object:ProductColor \n  attributes: \n    name: Green\n    created_at: 2009-06-10 04:02:44\n    updated_at: 2009-06-10 04:02:44\n    id: \"4\"\n    internal_name: Green\n  attributes_cache: {}\n\n"

Pensamientos?

Author: sth, 2009-08-04

11 answers

El método y es una forma práctica de obtener una salida YAML bastante.

y ProductColor.all

Asumiendo que estás en script/console

Como comentó jordanpg, esta respuesta está desactualizada. Para Rails 3.2 + necesita ejecutar el siguiente código antes de que pueda hacer funcionar el método y:

YAML::ENGINE.yamler = 'syck'

De ruby-docs

En versiones anteriores de Ruby, es decir.

Para rieles 4 / ruby 2 podrías usar solo

puts object.to_yaml
 237
Author: ryanb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 11:55:40

Deberías probar hirb. Es una gema hecha para formatear objetos bonitos en la consola ruby. Su sesión de script / consola se vería así:

>> require 'hirb'
=> true
>> Hirb.enable
=> true
>> ProductColor.first
+----+-------+---------------+---------------------+---------------------+
| id | name  | internal_name | created_at          | updated_at          |
+----+-------+---------------+---------------------+---------------------+
| 1  | White | White         | 2009-06-10 04:02:44 | 2009-06-10 04:02:44 |
+----+-------+---------------+---------------------+---------------------+
1 row in set
=> true

Puede obtener más información sobre hirb en su página de inicio .

 91
Author: cldwalker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-04 06:57:51

Awesome print también es bueno si quieres un objeto con sangría. Algo como:

$ rails console
rails> require "awesome_print"
rails> ap Account.all(:limit => 2)
[
    [0] #<Account:0x1033220b8> {
                     :id => 1,
                :user_id => 5,
            :assigned_to => 7,
                   :name => "Hayes-DuBuque",
                 :access => "Public",
                :website => "http://www.hayesdubuque.com",
        :toll_free_phone => "1-800-932-6571",
                  :phone => "(111)549-5002",
                    :fax => "(349)415-2266",
             :deleted_at => nil,
             :created_at => Sat, 06 Mar 2010 09:46:10 UTC +00:00,
             :updated_at => Sat, 06 Mar 2010 16:33:10 UTC +00:00,
                  :email => "[email protected]",
        :background_info => nil
    },
    [1] #<Account:0x103321ff0> {
                     :id => 2,
                :user_id => 4,
            :assigned_to => 4,
                   :name => "Ziemann-Streich",
                 :access => "Public",
                :website => "http://www.ziemannstreich.com",
        :toll_free_phone => "1-800-871-0619",
                  :phone => "(042)056-1534",
                    :fax => "(106)017-8792",
             :deleted_at => nil,
             :created_at => Tue, 09 Feb 2010 13:32:10 UTC +00:00,
             :updated_at => Tue, 09 Feb 2010 20:05:01 UTC +00:00,
                  :email => "[email protected]",
        :background_info => nil
    }
]

Para integrarlo de forma predeterminada con su consola irb/rails/pry, agregue a su archivo ~/.irbrc o ~/.pryrc:

require "awesome_print"
AwesomePrint.irb! # just in .irbrc
AwesomePrint.pry! # just in .pryrc
 18
Author: Alter Lagos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-19 21:46:58

También se puede señalar que se puede utilizar:

j ProductColor.all.inspect

A la salida en formato Json en lugar de Yaml

 10
Author: davidcollom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-24 10:51:58
>> puts ProductColor.all.to_yaml

Simplemente funciona bien!

Fuente: https://stackoverflow.com/a/4830096

 9
Author: Rody,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:41

Hola también puedes probar esto en tu script/consola si

>> y ProductColor.all

No funciona para ti.

Prueba esto:

>> require 'yaml'

>> YAML::ENGINE.yamler = 'syck'

Entonces

>> y ProductColor.all
 8
Author: Allen Chun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-06 07:41:01

Tuve algunos problemas para hacerlo funcionar, así que agregaré mis dos centavos a awesome_print agregue esto a su Gemfile, preferiblemente en :development

gem 'awesome_print', require: 'ap'

Luego en

rails console

Puedes hacer

> ap Model.all Eso es. Sin embargo, también puede agregar

require "awesome_print"
AwesomePrint.irb!

A su~/.irbrc, de esta manera awesome_print se requerirá cada vez que abra la consola y simplemente puede hacer

Modelo.todo sin necesidad de escribir ap

 6
Author: AndreiMotinga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-02 15:09:04

Utilice la gema irbtools.

Formateará automáticamente la salida de la consola, además de que obtendrá toneladas de excelentes características.

 5
Author: VivekVarade123,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-22 10:55:25

Es posible que desee definir el método inspect de ProductColor para devolver algo que encuentre agradable. Por ejemplo:

def inspect
  "<#{id} - #{name} (#{internal_name})>"
end

Después de lo cual el resultado de ProductColor.todo se mostrará como algo así como [, ...]. Por supuesto, debe ajustar el método inspect a sus necesidades, para que muestre toda la información que necesita en un estilo que le guste.

Editar: también si el problema fue la falta de saltos de línea en la salida, puede intentar

require 'pp'
pp ProductColor.all

Que debería insertar saltos de línea cuando proceda

 4
Author: sepp2k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-03 21:04:47

Para agregar a la sugerencia de Alter Lago para usar AwesomePrint, Si no puedes/no deberías/no quieres agregar la gema awesome_print al Gemfile de tu proyecto, haz esto:

gem install awesome_print

Editar ~/.irb.rc y añádase esto:

$LOAD_PATH << '/Users/your-user/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/gems/1.9.1/gems/awesome_print-1.1.0/lib'

require 'awesome_print'

(Asegurarse de que la ruta y la versión sean correctas, por supuesto)

 3
Author: Excalibur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-09 19:36:55

También puede probar lo siguiente para un grupo de objetos

Object.all.map(&:attributes).to_yaml

Esto te dará una salida mucho más agradable, como

---
id: 1
type: College
name: University of Texas
---
id: 2
type: College
name: University of California

Llamar a to_yaml en atributos en lugar del objeto en sí le evita ver el contenido completo del objeto en la salida

O puts Object.last.attributes.to_yaml para un solo objeto

La abreviatura también está disponible: y Object.last.attributes

 3
Author: Abram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-14 21:38:07