LoginSignup
2
2

More than 3 years have passed since last update.

Rails6(6.0.0-rc1)でActionView::Base#renderを直接呼ぶ方法

Last updated at Posted at 2019-07-10

環境

Ruby 2.6.3
Rails 6.0.0-rc1

ActionView::Base#render

例えばサービスクラスからAPIへ投稿する文章を組み立てたい
例えばActiveJobの中で文章を組み立てたい

そんなActionControllerやActionMailer以外で
ActionView::Base#renderを使いたいという時があります

Rails5迄の挙動とRails6での挙動が少し変わっていたのでメモしてみました

ファイル構成

.
└── apps
    └── views
        └── test
            ├── _partial.html.erb
            └── app.html.erb

Rails5までの場合

view = ActionView::Base.new
view.view_paths = Rails.root.join('app', 'views')
output_buffer = view.render(template: 'test/app')

Rails6.0.0-rc1

context = ActionView::LookupContext.new(Rails.root.join('app', 'views'))
view = ActionView::Base.new(context)
view.view_paths
output_buffer = view.render(template: 'test/app')

直接view_pathsをアサインしようとすると例外が発生します。
ActionView::Baseのコンストラクタに渡すLookupContextにpathを設定することでview_pathsが設定できました。

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