Skip to content

Conversation

@kmayer
Copy link

@kmayer kmayer commented May 28, 2022

Useful if you have an application that would like to sleep at the end
of every loop. This will let it wait for & collect the keypress until the
sleep would have expired.

For example, this loop will sleep until approximately the start of the next
second on the system clock.

loop do
  draw
  now = Time.now.to_f
  codes = reader.read_keypress(raw: true, nonblock: (now.ceil(0) - now))
  command.interpret(codes) if codes
end

Describe the change

Overload the semantics of the nonblock so that it can take a timeout value as well as Boolean.

Why are we doing this?

I'm building an application that is like top: It updates the terminal screen at 1 second intervals, and
needs to listen to keyboard commands. I was having trouble capturing the key presses in my event loop.
I had a sleep in the loop, but then I noticed that Console#get_char# has a TIMEOUT` constant.

Benefits

This adds a useful feature for writing looping applications.

Drawbacks

Not supported in win_console.

This may not be the best approach for this type of application. I did a bunch of experimentation before I
got this to work to my satisfaction.

There are no tests around the nonblock option, and I'm not sure how to test a timeout option without
introducing something like the Timecop gem to the development environment.

Requirements

  • Tests written & passing locally?
  • Code style checked?
  • Rebased with master branch?
  • Documentation updated?
  • Changelog updated?

Useful if you have an application that would like to sleep at the end
of every loop. This will let it wait for & collect the keypress until the
sleep would have expired.

For example, this loop will sleep until approximately the start of the next
second on the system clock.

```
loop do
  draw
  now = Time.now.to_f
  codes = reader.read_keypress(raw: true, nonblock: (now.ceil(0) - now))
  command.interpret(codes) if codes
end
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant