jbuilderのtemplateを使ってhashを取得

grape-jbuilderの環境でapi/view/api/users/index.jbuilderを使ってjsonを返しているエンドポイントがある。
これをcontrollerでhashで取得したい場合。

またapi/view/api/users/index.jbuilderでは@usersを使って値を取り出している。

config/application.rbに以下の設定を想定

1
2
3
4
5
class Application < Rails::Application
  config.middleware.use(Rack::Config) do |env|
    env['api.tilt.root'] = Rails.root.join 'app', 'views', 'api'
  end
end

コントローラーでの取り出し例

1
2
3
@users = User.all
engine = ::Tilt.new(request.env['api.tilt.root'] / 'users/index.jbuilder', nil, view_path: request.env['api.tilt.root'])
hash = JSON.parse(engine.render(self))

Comments