Using “ApplicationController.new.render_to_string” in a Rails api app (config.api_only = true)


Using “ApplicationController.new.render_to_string” in a Rails api app (config.api_only = true)



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.


ApplicationController.new.render_to_string


" "



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



This question has not received enough attention.





Try this maybe? evilmartians.com/chronicles/…
– Sergio Tulentsev
Jun 28 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
2 days ago


" "


Rails.logger.error ApplicationController.render(inline: 'erb content').inspect # => " "





Does this help? stackoverflow.com/questions/43911928/…
– Tarun Lalwani
yesterday




1 Answer
1



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





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
7 hours ago


ActionController::Base






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV