0

I am working on a rather lengthy seed.rb file.

Since it takes the rake task a while to complete, I want to give visual feedback through the console to the user so they know the process is working.

So far, I have:

puts "Topic: #{i}, created..."

inside the create loop. However, it spams the terminal output. What I would like to do is have the output look like this:

Topic: #1..N, created...

where the output all stays on the same line, without creating a /n newline character, like what the current output looks like:

Topic: #1, created...
Topic: #2, created...
Topic: #3, created...
Topic: #N, created...

I have tried fiddling with print instead, but it just creates a long string wrapping at the end of the terminal line.

This is the entire seed.rb code:

topic_list = []
i = 1
(0..9).map{
  topic_list << [ Faker::Lorem.words(rand(2..5)), Faker::Lorem.sentences(rand(3..7)), rand(1..6) ]
}
topic_list.each do |title, content, author|
  Topic.create!( title:title, content:content, author:author )
  puts "Topic: #{i}, #{title} created..."
  i += 1
end

Any ideas?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Matteo
  • 1,136
  • 1
  • 16
  • 36
  • 2
    You can do this with the help of the carriage return character. Refer to this answer: http://stackoverflow.com/questions/4963717/how-to-overwrite-a-printed-line-in-the-shell-with-ruby – anujm May 24 '16 at 21:20

1 Answers1

0

Dealing with the console is old school, and very different than working with browsers and HTML rendered pages.

The console uses carriage-control characters like "\t", "\r", "\n". There are others, but those are the most commonly used.

"\r" and "\n" go hand-in-hand. "\r" means return the carriage to its home position, and "\n" means advance to the next line. In a terminal "\r" results in moving the cursor to the left-most position.

Save this to a script and run it at the command-line:

print "foo\r"
sleep 1
print "bar\r"
sleep 1
puts "done"

You'll see "foo" printed, with the cursor over "f", then "bar", with the cursor over "b", then "done" printed and the cursor will move the next line.

puts behaves differently than print; Why is left for you to discover.

Also, simply appending "\r" isn't sufficient to generate a good looking progress message if some line's lengths are shorter than others. There are many different tutorials on the internet about how to deal with this, and I'm sure there are Ruby packages. Some searching should reveal those.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303