Rails 3 render plaintext page using view
Asked Answered
T

1

1

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?

Toothpick answered 25/9, 2012 at 21:47 Comment(1)
That seems like it should work. Are you sure the stray tags aren't the result of using helpers that generate HTML in your view?Atony
P
8

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.

Pantalets answered 26/9, 2012 at 8:28 Comment(4)
Thank you. Ctrl-U showed that what I have already is correct. The HTML tags were being inserted by Firebug. The Mime Type registration is a great tidbit, because it seemed silly that Rails doesn't have an inbuilt plaintext option for respond_to.Toothpick
Do you really need to add the mime-type plaintext if you are just using text ? Won't rails understand that mime-type, and set it to text/plain ?Tableware
Obviously it is even so that .text works out of the box without registering a new mimetype. Check out Mime::EXTENSION_LOOKUP["text"] from within your rails console. So you're more than right.Pantalets
@Pantalets Would you add that last comment to your answer?Snivel

© 2022 - 2024 — McMap. All rights reserved.