Awesome Printの使い方 まとめ
- 自分用のメモを公開したものです。ドキュメント/ソースコード等をまとめただけで試していないコードも多いので、信頼性は低いです。
Awesome Printとは
- コンソールやログ等の出力が見やすくするgem。いい感じにインデントを追加してくれたり、カラーリングしてくれたりする。
導入
インストール
group :development do gem "awesome_print" end
$ bundle install
使ってみる
$ rails console
# 色付きで、いい感じのインデントで出力 ap Cat.first
メソッド
ap(object): オブジェクトを見やすく出力
ap Cat.first
object.ai: オブジェクトを見やすく加工
- apの戻り値版
使い方
obj.ai obj.ai(plain: false) # 色付けしない obj.ai(html: false) # htmlに加工しない
オプション
indent: 4, # Number of spaces for indenting.
index: true, # Display array indices.
html: false, # Use ANSI color codes rather than HTML.
multiline: true, # Display in multiple lines.
plain: false, # Use colors.
raw: false, # Do not recursively format instance variables.
sort_keys: false, # Do not sort hash keys.
sort_vars: true, # Sort instance variables.
limit: false, # Limit arrays & hashes. Accepts bool or int.
ruby19_syntax: false, # Use Ruby 1.9 hash syntax in output.
color: {
args: :pale,
array: :white,
bigdecimal: :blue,
class: :yellow,
date: :greenish,
falseclass: :red,
fixnum: :blue,
float: :blue,
hash: :pale,
keyword: :cyan,
method: :purpleish,
nilclass: :red,
rational: :blue,
string: :yellowish,
struct: :pale,
symbol: :cyanish,
time: :greenish,
trueclass: :green,
variable: :cyanish
}
string.red: 文字を赤色にする
使い方
- 文字列のみ
- purpleとか他の色もok
"cat is kawaii".red #=> "\e[1;31mcat is kawaii\e[0m" puts "cat is kawaii".red # -> cat is kawaii
colorの種類
- gray
- red
- green
- yellow
- blue
- purple
- cyan
- white
- black
- redish
- greenish
- yellowish
- blueish
- purpleish
- cyanish
- pale
logger.ap(message): Awesome Printを使い、ログ吐き
使い方
- LoggerとActiveSupport::BufferedLoggerにapメソッドを加える
- そのためRailsデフォルトloggerでこんな感じで利用できる
- デフォルトは:debugレベル。変更可能
logger.ap @users # 出力 [ [0] #<User:0x00007fcce9d38d18> { :id => 1, :first_name => nil, :last_name => nil, :email => nil, :created_at => Fri, 31 Aug 2018 07:16:07 UTC +00:00, :updated_at => Fri, 31 Aug 2018 07:16:07 UTC +00:00 } ]
ログレベル指定(全体)
AwesomePrint.defaults[:log_level]
ログレベル指定(個別)
logger.ap @users, :warn
ap_debug(object): Awesome Printを使い、debug
- ActionView::Baseにapメソッドを追加するので、ビューでapが利用できる
- 色付けして、
<pre debug_dump>
で囲む <pre>
タグで囲むので、<%== %>
でHTMLエスケープしないようにする- debugに近い(こっちはyaml)
<%== ap @users %> <%== ap_debug @users %> <%== debug @users %>
オプション
グローバル
# ~/.apr AwesomePrint.defaults = { :indent => -2, :color => { :hash => :pale, :class => :white } }
個別
obj.ai(plain: false) # 色付けしない
REPLとの統合
irb
# ~/.irbrc require "awesome_print" AwesomePrint.irb!
pry
# ~/.pryrc require "awesome_print" AwesomePrint.pry!
# 通常時 pry(main)> [1, 2] => [1, 2]
# AwesomePrint.pry!時 pry(main)> [1, 2] [ [0] 1, [1] 2 ]