LoginSignup
2

More than 5 years have passed since last update.

pryでセッション開始前に変数をプリセットしておく(rails console対応)

Last updated at Posted at 2016-08-09

やりたいこと

rails cでREPLを使いつつコーディングするとき、毎回DBの同じレコードを使っている、つまり毎回

u = User.find(1)
u.some_method   # some_methodの動作確認

のようなことをしている。このu = User.find(1)を入力するのが面倒なので、rails cを開始したとき変数uをプリセットおきたい。

やり方

※以前はpryのフックを使う方法を書いていましたが、それだとpryの1コマンドごとに呼ばれてしまうので変更しました。

.pryrcに以下を記述。

@u = nil
def u
  if @u.nil?
    @u = User.find(1)
  end
  return @u
end
def u=(u)
  @u = u
end

これでuが使えるようになった。

[1] pry(main)> u

解説

pryにはフックの仕組みがあり、
:when_started :before_session :after_read :before_eval :after_eval :after_session
が用意されている。
https://github.com/pry/pry/wiki/Hooks#Hooks_index_of_built_in_events

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
2