1 Basic Usage Example
VetheonGames edited this page 2023-06-08 11:42:21 -06:00

Basic Usage Examples

The DynamicCursesInput gem is designed to be easy to use. Here are some basic usage examples.

Example 1: Basic Input Capture

This example shows how to capture user input using the DynamicCursesInput gem.

require "curses"
require "dynamic_curses_input"

Curses.init_screen
Curses.start_color
Curses.init_pair(1, Curses::COLOR_WHITE, Curses::COLOR_BLUE)
Curses.stdscr.bkgd(Curses.color_pair(1))
Curses.addstr("Enter your name: ")
name = DynamicCursesInput::InputHandler.catch_input(true)
Curses.addstr("\nYou entered: #{name}")
Curses.getch
Curses.close_screen

In this example, we initialize the curses screen, set the color, and then use the catch_input method from the InputHandler class to capture the user's input. The input is then displayed back to the user.

Example 2: Input Capture with Echo Disabled

This example shows how to capture user input with echo disabled.

require "curses"
require "dynamic_curses_input"

Curses.init_screen
Curses.start_color
Curses.init_pair(1, Curses::COLOR_WHITE, Curses::COLOR_BLUE)
Curses.stdscr.bkgd(Curses.color_pair(1))
Curses.addstr("Enter your password: ")
password = DynamicCursesInput::InputHandler.catch_input(false)
Curses.addstr("\nYou entered: #{'*' * password.length}")
Curses.getch
Curses.close_screen

In this example, we use the catch_input method with echo disabled (by passing false as the argument). This is useful for capturing sensitive information like passwords.

Example 3: Using the Shorthand DCI

This example shows how to use the shorthand DCI to call the InputHandler class.

require "curses"
require "dynamic_curses_input"

Curses.init_screen
Curses.start_color
Curses.init_pair(1, Curses::COLOR_WHITE, Curses::COLOR_BLUE)
Curses.stdscr.bkgd(Curses.color_pair(1))
Curses.addstr("Enter your name: ")
name = DCI.catch_input(true)
Curses.addstr("\nYou entered: #{name}")
Curses.getch
Curses.close_screen

In this example, we use DCI.catch_input(true) to capture the user's input. DCI is the shorthand for DynamicCursesInput that is included in the gem by default.