今回はpretty_printシリーズ(通称PP)のメモ。
整形してログを見やすくするクラスです。
このクラス自体はruby/2.3.0/pp.rb
に入っているので確認して見ましょう。
では早速何が良さげか見てましょう。
まずは普通のprintから
1 2 3 |
>> p User.first User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] #<User id: 1, name: "aa", created_at: "2017-04-11 14:41:57", updated_at: "2017-04-11 14:41:57"> |
ですね。横長で見づらい。。
次にpretty_printを使う。
1 2 3 4 5 6 7 8 |
> PP.pp User.first User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] #<User:0x007fb2798023b0 id: 1, name: "aa", created_at: Tue, 11 Apr 2017 14:41:57 UTC +00:00, updated_at: Tue, 11 Apr 2017 14:41:57 UTC +00:00> #<IO:<STDOUT>> |
こんな感じで項目ごとに律儀に改行してくれてる!
見やすくなってる!
したの方法でもOK。クラスから呼ばなくても呼べるので楽。
1 2 3 4 5 6 7 8 |
> pp User.first User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] #<User:0x007fb27653f338 id: 1, name: "aaa", user_id: 1, created_at: Tue, 11 Apr 2017 15:11:56 UTC +00:00, updated_at: Tue, 11 Apr 2017 15:13:03 UTC +00:00> |
そんな感じです。
pretty_inspect
inspectのプリティ版
1 2 3 4 5 6 7 |
> User.first.inspect User Load (0.7ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] "#<User id: 1, name: \"aa\", created_at: \"2017-04-11 14:41:57\", updated_at: \"2017-04-11 14:41:57\">" > User.first.pretty_inspect User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] "#<User:0x007fb27904a488\n id: 1,\n name: \"aa\",\n created_at: Tue, 11 Apr 2017 14:41:57 UTC +00:00,\n updated_at: Tue, 11 Apr 2017 14:41:57 UTC +00:00>\n" |
ちょっと見やすい気がする。
ちなみにこれでもできる。/n
が入るか入らないかの違い。
1 2 3 |
> User.first.pretty_print_inspect User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] "#<User:0x007fb276b29ed8 id: 1, name: \"aa\", created_at: Tue, 11 Apr 2017 14:41:57 UTC +00:00, updated_at: Tue, 11 Apr 2017 14:41:57 UTC +00:00>" |
pretty_print_instance_variables
インスタンス変数一覧をみるメソッド
1 2 3 4 5 6 7 |
> User.first.instance_variables [:@attributes, :@aggregation_cache, :@association_cache, :@readonly, :@destroyed, :@marked_for_destruction, :@destroyed_by_association, :@new_record, :@txn, :@_start_transaction_state, :@transaction_state] User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] > User.first.pretty_print_instance_variables [:@_start_transaction_state, :@aggregation_cache, :@association_cache, :@attributes, :@destroyed, :@destroyed_by_association, :@marked_for_destruction, :@new_record, :@readonly, :@transaction_state, :@txn] User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] |
ほとんど変わってない。
なぜならpretty_print_instance_variables
はinstance_variables
をソートしているだけだからだッ!!
あとがき
まぁbinding.pryの時は使わないと思いますが、
rails consoleの時は割と重宝するのではないでしょうか。
PP.ppがPPAPっぽかったので書いた記事。
参考
.rbenv/versions/2.3.0/lib/ruby/2.3.0/pp.rb
スポンサードリンク