Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: How to render file as plain text (without any HTML)

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.

like image 497
wrystr Avatar asked Jan 15 '14 05:01

wrystr


People also ask

How can you tell Rails to render without a layout?

By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.

What is Local_assigns?

local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not. Here you render a partial with some values, the headline and person will become accessible with predefined value.

What is render partial in Rails?

Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

What are layouts in Rails?

In Rails, layouts are pieces that fit together (for example header, footer, menus, etc) to make a complete view. An application may have as many layouts as you want. Rails use convention over configuration to automatically pair up layouts with respective controllers having same name.


2 Answers

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.

like image 144
mecampbellsoup Avatar answered Oct 27 '22 21:10

mecampbellsoup


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

send_file path_to_file
like image 33
Abs Avatar answered Oct 27 '22 20:10

Abs