やりたいこと
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