Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - Redirecting console output to a file

On a bash console, if I do this:

cd mydir ls -l > mydir.txt 

The > operator captures the standard input and redirects it to a file; so I get the listing of files in mydir.txt instead of in the standard output.

Is there any way to do something similar on the rails console?

I've got a ruby statement that generates lots of prints (~8k lines) and I'd like to be able to see it completely, but the console only "remembers" the last 1024 lines or so. So I thought about redirecting to a file - If anyone knows a better option, I'm all ears.

like image 543
kikito Avatar asked Mar 17 '10 10:03

kikito


2 Answers

You can use override $stdout to redirect the console output:

$stdout = File.new('console.out', 'w') 

You may also need to call this once:

$stdout.sync = true 

This will redirect all output to the file. If you want to temporarily redirect the output make sure that you store the original value of $stdout so you can change it back.

like image 26
Veger Avatar answered Sep 24 '22 23:09

Veger


A quick one-off solution:

irb:001> f = File.new('statements.xml', 'w') irb:002> f << Account.find(1).statements.to_xml irb:003> f.close 

Create a JSON fixture:

irb:004> f = File.new(Rails.root + 'spec/fixtures/qbo/amy_cust.json', 'w') irb:005> f << JSON.pretty_generate((q.get :customer, 1).as_json) irb:006> f.close 
like image 187
Minimul Avatar answered Sep 25 '22 23:09

Minimul