LoginSignup
29
30

More than 5 years have passed since last update.

Hirbを使ってRailsコンソール上のモデル出力を表形式に整形

Last updated at Posted at 2015-10-02

rails console上でモデルの内容を出力したら、配列のように出力されてみにくい。Hirbを使用することで、データベースのコンソール上で実行したような表形式での出力を整形することができる。

Hirbを利用できるようにする

GemfileにHirbを追加する

group :development, :test do
  gem 'hirb'
  gem 'hirb-unicode'
end

Bundlerでgemをインストールする

bundle install

デフォルトではHirdは有効になっていないので、Railsコンソールを開いてHirbを有効する。
有効にする:Hirb.enable
無効にする:Hirb.disable

$ rails c
Loading development environment (Rails 4.2.3)
irb: warn: can't alias context from irb_context.
irb(main):001:0> MasterJob.first
  MasterJob Load (0.3ms)  SELECT  `master_jobs`.* FROM `master_jobs`  ORDER BY `master_jobs`.`id` ASC LIMIT 1
=> #<MasterJob id: 1, name: "取締役", deleted_at: nil, created_at: "2015-09-09 02:03:25", updated_at: "2015-09-09 02:03:25">
irb(main):002:0> Hirb.enable
=> true
irb(main):003:0> MasterJob.first
  MasterJob Load (0.3ms)  SELECT  `master_jobs`.* FROM `master_jobs`  ORDER BY `master_jobs`.`id` ASC LIMIT 1
+----+--------+------------+---------------------------+---------------------------+
| id | name   | deleted_at | created_at                | updated_at                |
+----+--------+------------+---------------------------+---------------------------+
| 1  | 取締役 |            | 2015-09-09 11:03:25 +0900 | 2015-09-09 11:03:25 +0900 |
+----+--------+------------+---------------------------+---------------------------+
1 row in set
irb(main):004:0>

PryでHirb

railsプロジェクトのルートディレクトリに.pryrcファイル作成する(Gemfileと同じ場所)。
.pryrcに下記を書いて保存すれば使用できるようになっていまいす。

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
29
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
30