9

How do you render file as a plain/text in rails (without rendering any HTML)?

I've tried:

render file: "path/to/file", layout: false

and

render file: "path/to/file", content_type: 'text/plain'

also both

render file: "path/to/file", layout: false, content_type: 'text/plain'

But there still some html on the response.

I'm using rails 3.2.14 and ruby 1.9.3

Thanks in advance.

EDIT 1:

Silly me, this actually works:

render file: "path/to/file", layout: false, content_type: 'text/plain'

I was inspecting the element using google chrome, so there's an html tag appears. But when I see the source, there's no HTML tag.

The file I was trying to render is a custom made file without extension, it is a tab separated value I use as a parameter in d3.tsv() (D3.js)

Thank you all for your efforts. :D

EDIT 2:

In Edit 1, I checked the response and it's true that it doesn't come with any html tag. But using it as parameter in d3.tsv() (D3.js) doesn't work apparently. Glad I tried the answer from JetAbe and it works! So I accepted JetAbe's answer.

Community
  • 1
  • 1
wrystr
  • 101
  • 1
  • 1
  • 6
  • what is getting rendered? `layout: false` will apply no layout meaning whats in that file is what you get. – sevenseacat Jan 15 '14 at 05:15
  • Have a look here http://stackoverflow.com/questions/12591566/rails-3-render-plaintext-page-using-view – Abs Jan 15 '14 at 05:28
  • instead of editing your question , answer it and mark as accepted.so that others know that its solved and don't waste time. – Anil Maurya Jan 15 '14 at 06:15
  • I'm newbie, can't post my own answer. – wrystr Jan 15 '14 at 08:30
  • You should be able to do so now. Welcome to Stack Overflow! If you need any further help in this Q drop me a line (either by adding @AngeloNeuschitzer to a comment here or write me an email, see my profile) – Angelo Fuchs Feb 26 '14 at 18:37

2 Answers2

9

Rails 4.1 now exposes the following API for the render method:

render :plain will set the content type to text/plain render :html will set the content type to text/html render :body will not set the content type header.

In fact, they'll be deprecating use of render: text in a future release.

mecampbellsoup
  • 1,260
  • 18
  • 16
  • For future searchers: In rails 4.0.0, in order to render text you need to write: `render text: "some text"`. :plain does not work. – 7stud Jan 12 '15 at 00:15
  • 1
    @7stud The opposite appears true. "We will be deprecating the use of render :text in a future version. So please start using the more precise :plain, :html, and :body options instead. Using render :text may pose a security risk, as the content is sent as text/html." See: http://guides.rubyonrails.org/upgrading_ruby_on_rails.html#rendering-content-from-string – R. P. Dillon Jul 12 '15 at 22:38
5

I think because your env is rails 3 you can try this

send_file path_to_file
Abs
  • 3,902
  • 1
  • 31
  • 30