1

I have a Rails 5 app build as an api app:

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.api_only = true
  end
end

In one of my controller actions I need to render some Ruby flavoured html, and then serve it back in the json response.

A standard Rails app do this:

# app/controllers/my_controller.rb
def my_action
  html = ApplicationController.new.render_to_string("my_erb_or_haml_file", locals: {foo: "bar"}, layout: false)
  render :json => {html: html}, :status => :ok
end

However, for my slimmed api app ApplicationController.new.render_to_string seems to just render " ". This confuses me, because I would expect it to either serve the content or raise an exception.

Any suggestions what route I should take in order to generate Ruby flavoured html?

JohnSmith1976
  • 536
  • 2
  • 12
  • 35
  • Try this maybe? https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions – Sergio Tulentsev Jun 28 '18 at 11:52
  • @SergioTulentsev seems like regardless which of the suggested lines from that post I use, it renders `" "`, e.g. `Rails.logger.error ApplicationController.render(inline: 'erb content').inspect # => " "`. – JohnSmith1976 Jun 30 '18 at 17:23
  • Does this help? https://stackoverflow.com/questions/43911928/how-to-render-file-in-rails-5-api – Tarun Lalwani Jul 02 '18 at 05:12

1 Answers1

7

I guess you have to explicitly use base class. Your application is an API app, so your controller is probably inheriting from ActionController::API

ActionController::Base.new.render_to_string
Zzz
  • 1,703
  • 1
  • 14
  • 21
  • this seems to work. I also tried the suggestion of @TarunLalwani, to inherit that particular controller from `ActionController::Base`. It also worked. Which solution would be considered most lightweight? – JohnSmith1976 Jul 03 '18 at 05:41
  • I guess it depends on your use case, if you want to render the html directly, @Tarun lalwani answer is probably 'light weight'. but if you want to return a json that has rendered html as the body/content, ^ is probably more explicit and light weight given it is just a method call rather than whole inheritance of a class. – Zzz Jul 03 '18 at 23:12
  • Or just `ActionController::Base.render` – Lev Lukomsky Jul 28 '19 at 15:28