Rails 3 render plaintext page using view

无人久伴 提交于 2019-12-08 05:15:38

问题


I have a Linux configuration file stored in my database in Rails, and I'd like to be able to download the configuration through a web request

My goal on the Linux side is to curl/wget the webpage, compare it to the current configuration, and then hup the server. Easy enough to do in a script.

In normal circumstances on Rails, you could do

render :text => @config_file

However, I need to do some formatting of the data first to apply the static headers, etc. This isn't a one-liner, so I need to be able to render a view.

I have the following set in my controller, but I still get a minimal set of HTML tags in the document

render(:content_type => 'text/plain', :layout => false);

I've done something similar in .Net before, so it printed out a text file with \n interpreted. How do I get that in Rails?


回答1:


Normally, this is done with

# config/initializers/mime_types.rb
# ...
# Mime::Type.register "text/plain", :plaintext
# No changes needed as rails comes preconfigured with the text/plain mime type


# app/controllers/my_controller.rb

class MyController < ApplicationController
  def my_action
    respond_to do |format|
      format.text
    end
  end
end

and a view file

# app/views/my_controller/my_action.text.erb
...

About the minimal HTML you find in the DOM: Are you seeing this from within some kind of in-browser inspector, like the ones included in google chrome or safari? If so then don't worry, this is added by the browser in order to display your text/plain document inline. If you look at the source of the delivered document (ctrl-u) no HTML should show up.



来源:https://stackoverflow.com/questions/12591566/rails-3-render-plaintext-page-using-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!