LoginSignup
0
0

More than 5 years have passed since last update.

Railsの実行環境(modelなど)でconsoleのメソッドが使えるようにするための黒魔術

Posted at

TL;DR

其之壱

app = ActionDispatch::Integration::Session.new(Rails.application)
app.get root_path
app.body

其之弐

echo 'app.get app.root_path; puts app.body' | bundle exec rails c
# または
echo 'app.get app.root_path; puts app.body' | spring rails c

本文

Rails Consoleのメソッドについて

主は Rails::ConsoleMethods#app というメソッドが生成したappという汎用モジュールのことを指します。他のConsoleのみ使えるメソッドについてはまだ研究中です。

不特定Moduleで使う

rakeタスクやmodel、moduleで使うには、下記の構文で consoleしか存在しない app というインスタンスを作れます。
Classの中でUrl Helperを使う方法はこちらの記事を参考してください

class Foo
  include Rails.application.routes.url_helpers

  def magic_method
    app = ActionDispatch::Integration::Session.new(Rails.application)
    app.get root_path
    app.body
  end
end

Shellから呼び出す

echo 'app.get app.root_path; puts app.body' | bundle exec rails c
# または
echo 'app.get app.root_path; puts app.body' | spring rails c

:warning:注意:warning:

黒魔術ゆえ、無闇に使うと、保守性が劇的に下がる上、事故に根源にもなりえます!

参考

https://stackoverflow.com/a/28599867
https://stackoverflow.com/a/25128213
https://qiita.com/mt2/items/072cce9be652cf2dd743
https://qiita.com/jerrywdlee/items/f91c9ea01055cb74083c

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