views:

443

answers:

3

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.

+2  A: 

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

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

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

Veger
Thank you! This is exactly what I was looking for.
egarcia
+1  A: 

If you write the following code in your environment file, it should work.

if "irb" == $0
  config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))
end

You can also rotate the log file using

config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'), number_of_files, file_roation_size_threshold)

For logging only active record related operations, you can do

ActiveRecord::Base.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))

This also lets you have different logger config/file for different environments.

Chirantan
This is helpful, but the other answer does what I wanted in a simpler way. Thanks for taking the time to answer anyway.
egarcia
A: 

Use hirb. It automatically pages any output in irb that is longer than a screenful. Put this in a console session to see this work:

>> require 'rubygems'
>> require 'hirb'
>> Hirb.enable

For more on how this works, read this post.

Thanks for answering, but I wasn't looking for pagination; I wanted to see everything on a single page.
egarcia