Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a text file from a String for download in Ruby on Rails

I'm building a website using Rails and I have a Model with some text type value store in MySQL database, I need to provide a download link for my users to download a "*.txt" file which contains those texts.

what I've tried is to use render :text => my_text but it's kind of ugly and the browser can't start a download .

Not I'm trying to use CarrierWave and mount a output_file to my model , I want to build a method to generate a file from its text value. Any suggestion would be greatly appreciated. Thanks!

like image 861
Chaoyu Avatar asked Apr 12 '12 10:04

Chaoyu


People also ask

How do you download a file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.

How do I download text data from a website?

Click and drag to select the text on the Web page you want to extract and press “Ctrl-C” to copy the text. Open a text editor or document program and press “Ctrl-V” to paste the text from the Web page into the text file or document window. Save the text file or document to your computer.

How do I download a file in rails?

To offer files for download, use send_file . Note that a send_file replaces the default :render action.


1 Answers

send_data 'text to send', :filename => 'some.txt'

Documentation Here

like image 156
jdoe Avatar answered Sep 28 '22 10:09

jdoe