Railsメモ(3) : rails consoleを使いやすくする
rails consoleを使いやすくしたり、見やすくしてみる。
いろいろと調べたところ以下のキーワードが引っかかったのでそれぞれ試してみる。
- pry-rails
- Hirb
- awesome_print
pry-rails
rails consoleをirbからPryに変更する。
Gemfileにpry-rails
を追加してbundle install
する。
group :development, :test do gem 'pry-rails' end
rails consoleを起動するとPryに変更されており、help
を打つと利用可能なコマンドが確認できる。例えば全てのモデルの定義を見るには下記コマンドを実行する。
[1] pry(main)> show-models Song id: integer title: string display_artist: string ranking: integer year: integer created_at: datetime updated_at: datetime
Hirb
Hirbを使って出力を表形式にする。
Gemfileにhirb
とhirb-unicode
を追加してbundle install
する。
hirb-unicode
は日本語などマルチバイト文字が入る場合に出力が乱れないようにするために必要。
group :development, :test do gem 'hirb' gem 'hirb-unicode' end
rails consoleにPryを使用している場合、このままでは起動時にHirbが有効にならないため.pryrc
に下記設定(PryのWiki参照)を記述してホームディレクトリかプロジェクト直下に配置しておく。
begin require 'hirb' rescue LoadError # Missing goodies, bummer end if defined? Hirb # Slightly dirty hack to fully support in-session Hirb.disable/enable toggling Hirb::View.instance_eval do def enable_output_method @output_method = true @old_print = Pry.config.print Pry.config.print = proc do |*args| Hirb::View.view_or_page_output(args[1]) || @old_print.call(*args) end end def disable_output_method Pry.config.print = @old_print @output_method = nil end end Hirb.enable end
これでHirbが起動時に有効になり、以下のように出力が表形式になる。一時的にHirbを無効にしたい場合はHirb.disable
を実行。再度有効にしたい場合はHirb.enable
を実行。
[1] pry(main)> Song.all Song Load (1.6ms) SELECT "songs".* FROM "songs" +----+------------+------------------------------+---------+------+-------------------------+-------------------------+ | id | title | display_artist | ranking | year | created_at | updated_at | +----+------------+------------------------------+---------+------+-------------------------+-------------------------+ | 1 | Happy | Pharrell Williams | 1 | 2014 | 2015-08-04 11:34:44 UTC | 2015-08-04 11:34:44 UTC | | 2 | Dark Horse | Katy Perry featuring Juicy J | 2 | 2014 | 2015-08-04 11:35:38 UTC | 2015-08-04 11:35:38 UTC | | 3 | All of Me | John Legend | 3 | 2014 | 2015-08-04 11:36:15 UTC | 2015-08-04 11:36:15 UTC | +----+------------+------------------------------+---------+------+-------------------------+-------------------------+ 3 rows in set
awesome_print
awesome_printを使うと色付きで綺麗にインデントして表示される。
Gemfileにawesome_print
を追加してbundle install
する。
group :development, :test do gem 'awesome_print' end
awesome_print
も起動時にデフォルトでは有効にならないため.pryrc
に下記設定(PryのWiki参照)を記述してホームディレクトリかプロジェクト直下に配置しておく(Hirbの設定を優先したいので、awesome_printの設定はHirbの設定の前に記述しておく)。
begin require 'awesome_print' Pry.config.print = proc { |output, value| output.puts value.ai } rescue LoadError => err puts "no awesome_print :(" end
これでawesome_printが起動時に有効になり、以下のような表示になる。なお、Hirbが有効でも先頭にap
を付ければ出力がawesome_print形式になる。
- 作者: すがわらまさのり,前島真一,近藤宇智朗,橋立友宏
- 出版社/メーカー: 技術評論社
- 発売日: 2014/06/06
- メディア: 大型本
- この商品を含むブログ (8件) を見る