A CLI (command line interface) application is one that takes place entirely within a computer’s terminal. The terminal is meant to do exactly two things: read user input, and write a response. No graphics, no complex interface, only text. While CLI applications are limited in what they can express to a user, they can still accomplish much more than one might think at first glance.

While creating my first CLI application in Ruby, the first hurdle I came across was in implementing time as a factor in my app. In a format that’s designed exclusively to respond to user input — no matter when it may arrive — how can an outside factor like time dictate how an application works?

Well, as it turns out, it can do so through a lot of different methods. The following are a number of ways to have CLI applications change over time, without necessary user input.

The sleep method

The easiest way to integrate time into a CLI application — or any Ruby application, for that matter — is by using the built-in sleep method. This method simply “pauses” the application for a specified number of seconds.

puts “This prints immediately”

sleep(5)
puts “This prints 5 seconds later”

Keep in mind that the argument it takes in is a float, not an integer. The method works just as well with only increments of seconds. Here’s a fun trick: in conjunction with an escape sequence like “\e[2J\e[f” that clears the terminal screen, quick sleeps can be used to effectively animate within the terminal.

print "\e[2J\e[f"

puts '  ___
{o,o}
|)__)
--"-"-- '
sleep(0.1)
print "\e[2J\e[f"
puts '  ___
{  o},
|)__)
--"-"-- '
sleep(0.1)
print "\e[2J\e[f"
puts '  ___
{   }
|)__)
--"-"--'
sleep(0.1)
print "\e[2J\e[f"
puts '  ___
{o  }
|)__)
--"-"--'
sleep(0.1)
print "\e[2J\e[f"
puts '  ___
{o,o}
|)__)
--"-"--

#cli #coding #flatiron-school #ruby

Time and the Command Line
1.40 GEEK