rails console まとめ

Rails で開発していると必ず使用する rails console
便利な機能が色々あるのでまとめてみました。

環境を指定して起動する

$ rails console [-e, --environment=name]

$ rails console -e test
$ rails console --environment=test
# デフォルトは development 環境になる
$ rails console
> Rails.env
=> "development"

# production 環境で起動する
$ rails console -e production
# $ rails console --environment=production こっちでもいい
> Rails.env
=> "production"

サンドボックスモードで起動する

サンドボックスモードで起動するとコンソール自体が一つのトランザクションになるため、 コンソール終了時にデータベースに関する変更をロールバックすることができます。

$ rails console [-s, --sandbox]
$ rails console --sandbox
> User.create(email: 'test@example.com', password: 'password')
> User.all # => #<ActiveRecord::Relation [#<User id: 1, email: "test@example.com", password: "password", created_at: "2014-11-28 13:29:50", updated_at: "2014-11-28 13:29:50">]>
> exit
   (2.5ms)  rollback transaction

$ rails console
> User.all # => #<ActiveRecord::Relation []>

リロードする

コンソール起動中にコードを変更した際には変更が反映されないので再読み込みしなければいけません。 「reload!」を使えばわざわざexitしなくても済みます。

$ rails console
> ....
> reload!
Reloading...
=> true

名前付きルートを確認する

> app.root_path
=> "/"

> app.root_url
=> "http://www.example.com/"

> app.url_for(controller: 'home', action: 'index')
=> "http://www.example.com/"

GETリクエストを投げる

> app.get '/'
> response = app.response
> response.body

ヘルパーメソッドを呼び出す

> view = ActionView::Base.new
> view.image_tag 'rails.png'
=> "<img alt=\"Rails\" src=\"/assets/rails.png\" />"

> view.stylesheet_link_tag 'application'
=> "<link href=\"/assets/application.css?body=1\" media=\"screen\" rel=\"stylesheet\" />"

定義したヘルパーメソッドを呼び出す

module ApplicationHelper
  def greet
    'Hello!'
  end
end
> helper.greet
Hello!

コンソールを使いやすくする gem

Hirb

cldwalker/hirb · GitHub
miaout17/hirb-unicode · GitHub

ActiveRecord の結果を見易い形式に整形してくれます。

# Gemfile

gem 'hirb'
gem 'hirb-unicode' # => HirbのUnicode対応版。日本語が入っていても結果がずれないようになります。
# Hirbを使わない場合
> Hirb.disable # 無効にする
> User.all
=> #<ActiveRecord::Relation [#<User id: 1, email: "user@example.com", name: "テストユーザー", created_at: "2014-11-28 13:46:10", updated_at: "2014-11-28 13:46:10">, #<User id: 2, email: "admin@example.com", name: "管理ユーザー", created_at: "2014-11-28 13:46:19", updated_at: "2014-11-28 13:46:19">]>

# Hirbを使った場合
> Hirb.enable # 有効にする
> User.all
+----+-------------------+----------------+-------------------------+-------------------------+
| id | email             | name           | created_at              | updated_at              |
+----+-------------------+----------------+-------------------------+-------------------------+
| 1  | user@example.com  | テストユーザー | 2014-11-28 13:46:10 UTC | 2014-11-28 13:46:10 UTC |
| 2  | admin@example.com | 管理ユーザー   | 2014-11-28 13:46:19 UTC | 2014-11-28 13:46:19 UTC |
+----+-------------------+----------------+-------------------------+-------------------------+

pry-rails

rweng/pry-rails · GitHub

rails consoleをirbからpryにする。

# Gemfile

gem 'pry-rails'
# ルーティングを確認する
> show-routes
Prefix Verb URI Pattern Controller#Action
  root GET  /           home#index

# スキーマ定義を確認する
> show-models
Profile
  id: integer
  nickname: string
  created_at: datetime
  updated_at: datetime
  belongs_to :user
User
  id: integer
  email: string
  name: string
  created_at: datetime
  updated_at: datetime
  has_one :profile

# モデルを指定することも可能
> show-model User
User
  id: integer
  email: string
  name: string
  created_at: datetime
  updated_at: datetime
  has_one :profile

# 使用しているミドルウェアを確認する
> show-middleware
use Rack::Sendfile
use ActionDispatch::Static
...

awesome_print

michaeldv/awesome_print · GitHub

オブジェクトを見易い形に整形して表示するメソッドを提供してくれます。

# Gemfile

gem 'awesome_print'
> require "awesome_print"
> data = [ false, 42, %w(forty two), { :now => Time.now, :class => Time.now.class, :distance => 42e42 } ]
=> [false, 42, ["forty", "two"], {:now=>2014-11-26 15:53:09 +0900, :class=>Time, :distance=>4.2e+43}]
> ap data
[
    [0] false,
    [1] 42,
    [2] [
        [0] "forty",
        [1] "two"
    ],
    [3] {
             :now => 2014-11-26 15:53:09 +0900,
           :class => Time < Object,
        :distance => 4.2e+43
    }
]