Module: Clack

Defined in:
lib/clack.rb,
lib/clack/box.rb,
lib/clack/log.rb,
lib/clack/note.rb,
lib/clack/group.rb,
lib/clack/utils.rb,
lib/clack/colors.rb,
lib/clack/errors.rb,
lib/clack/stream.rb,
lib/clack/symbols.rb,
lib/clack/testing.rb,
lib/clack/version.rb,
lib/clack/task_log.rb,
lib/clack/validators.rb,
lib/clack/core/chrome.rb,
lib/clack/core/cursor.rb,
lib/clack/core/prompt.rb,
lib/clack/environment.rb,
lib/clack/core/ci_mode.rb,
lib/clack/prompts/date.rb,
lib/clack/prompts/path.rb,
lib/clack/prompts/text.rb,
lib/clack/transformers.rb,
lib/clack/core/settings.rb,
lib/clack/prompts/range.rb,
lib/clack/prompts/tasks.rb,
lib/clack/prompts/select.rb,
lib/clack/core/key_reader.rb,
lib/clack/prompts/confirm.rb,
lib/clack/prompts/spinner.rb,
lib/clack/prompts/password.rb,
lib/clack/prompts/progress.rb,
lib/clack/core/fuzzy_matcher.rb,
lib/clack/core/scroll_helper.rb,
lib/clack/prompts/select_key.rb,
lib/clack/core/options_helper.rb,
lib/clack/prompts/multiselect.rb,
lib/clack/prompts/autocomplete.rb,
lib/clack/core/selection_manager.rb,
lib/clack/core/text_input_helper.rb,
lib/clack/prompts/multiline_text.rb,
lib/clack/prompts/group_multiselect.rb,
lib/clack/prompts/autocomplete_multiselect.rb

Overview

Clack - Beautiful CLI prompts for Ruby

A faithful Ruby port of @clack/prompts, bringing delightful terminal aesthetics to your Ruby projects.

Examples:

Basic usage

Clack.intro "Welcome to my-app"
name = Clack.text(message: "What's your name?")
exit 1 if Clack.cancel?(name)
Clack.outro "Nice to meet you, #{name}!"

Using prompt groups

result = Clack.group do |g|
  g.prompt(:name) { Clack.text(message: "Name?") }
  g.prompt(:confirm) { Clack.confirm(message: "Continue?") }
end

See Also:

Defined Under Namespace

Modules: Box, Colors, Core, Environment, Log, Note, Prompts, Stream, Symbols, Testing, Transformers, Utils, Validators Classes: Group, NotATerminalError, TaskLog, TaskLogGroup, Warning

Constant Summary collapse

CANCEL =

Sentinel value returned when user cancels a prompt (Escape or Ctrl+C)

Object.new.tap { |o| o.define_singleton_method(:inspect) { "Clack::CANCEL" } }.freeze
VERSION =

Current gem version.

"0.7.0"

Class Method Summary collapse

Class Method Details

.autocomplete(message:, options:, **opts) ⇒ Object, CANCEL

Prompt with type-to-filter autocomplete.

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash, String>, Hash)

    list of options to filter, or a Hash of value => label

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :placeholder (String, nil)

    placeholder text

  • :filter (Proc, nil)

    custom filter proc receiving (option_hash, query_string) and returning true/false. Defaults to fuzzy matching across label, value, and hint, sorted by relevance score.

  • :max_items (Integer, nil)

    max visible items (enables scrolling, default: 5)

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :show_instructions (Boolean, nil)

    show the keyboard hint footer (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Object, CANCEL)

    selected value or CANCEL if cancelled



373
374
375
# File 'lib/clack.rb', line 373

def autocomplete(message:, options:, **opts)
  Prompts::Autocomplete.new(message:, options: options, **opts).run
end

.autocomplete_multiselect(message:, options:, **opts) ⇒ Array, CANCEL

Prompt with type-to-filter autocomplete and multiselect.

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash, String>, Hash)

    list of options to filter, or a Hash of value => label

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :placeholder (String, nil)

    placeholder text

  • :required (Boolean)

    require at least one selection (default: true)

  • :initial_values (Array, nil)

    initially selected values

  • :filter (Proc, nil)

    custom filter proc receiving (option_hash, query_string) and returning true/false. Defaults to fuzzy matching across label, value, and hint, sorted by relevance score.

  • :max_items (Integer, nil)

    max visible items (enables scrolling, default: 5)

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :show_instructions (Boolean, nil)

    show the keyboard hint footer (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Array, CANCEL)

    selected values or CANCEL if cancelled



392
393
394
# File 'lib/clack.rb', line 392

def autocomplete_multiselect(message:, options:, **opts)
  Prompts::AutocompleteMultiselect.new(message:, options: options, **opts).run
end

.box(message = "", title: "", **opts) ⇒ void

This method returns an undefined value.

Display content in a customizable box.

Parameters:

  • message (String) (defaults to: "")

    the box content

  • title (String, nil) (defaults to: "")

    optional title

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :content_align (:left, :center, :right)

    content alignment

  • :title_align (:left, :center, :right)

    title alignment

  • :width (Integer, :auto)

    box width

  • :rounded (Boolean)

    use rounded corners

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)



574
575
576
# File 'lib/clack.rb', line 574

def box(message = "", title: "", **opts)
  Box.render(message, title: title, **opts)
end

.cancel(message = nil, with_guide: nil, output: $stdout) ⇒ void

This method returns an undefined value.

Display a cancellation message (typically after user presses Escape).

Parameters:

  • message (String, nil) (defaults to: nil)

    optional cancellation message

  • with_guide (Boolean, nil) (defaults to: nil)

    show the guide symbol (default: Clack.settings)

  • output (IO) (defaults to: $stdout)

    output stream (default: $stdout)



158
159
160
161
162
163
164
165
166
# File 'lib/clack.rb', line 158

def cancel(message = nil, with_guide: nil, output: $stdout)
  if Core::Settings.with_guide?(with_guide)
    output.puts Colors.gray(Symbols::S_BAR)
    output.puts "#{Colors.gray(Symbols::S_BAR_END)}  #{Colors.red(message)}"
  else
    output.puts Colors.red(message)
  end
  output.puts
end

.cancel?(value) ⇒ Boolean Also known as: cancelled?

Check if a prompt result was cancelled by the user.

Parameters:

  • value (Object)

    the result from a prompt

Returns:

  • (Boolean)

    true if the user cancelled



94
95
96
# File 'lib/clack.rb', line 94

def cancel?(value)
  value.equal?(CANCEL)
end

.ci?Boolean

Check if running in a CI environment

Returns:

  • (Boolean)


633
634
635
# File 'lib/clack.rb', line 633

def ci?
  Environment.ci?
end

.columns(output = $stdout, default: 80) ⇒ Integer

Get terminal columns (width)

Parameters:

  • output (IO) (defaults to: $stdout)

    Output stream

  • default (Integer) (defaults to: 80)

    Default if detection fails

Returns:

  • (Integer)


654
655
656
# File 'lib/clack.rb', line 654

def columns(output = $stdout, default: 80)
  Environment.columns(output, default: default)
end

.confirm(message:, **opts) ⇒ Boolean, CANCEL

Prompt for yes/no confirmation.

Examples:

Stacked layout

Clack.confirm(
  message: "Overwrite ~/.zshrc?",
  active: "Yes, back it up and replace it",
  inactive: "No, keep my existing file",
  vertical: true
)

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :active (String)

    label for "yes" option (default: "Yes")

  • :inactive (String)

    label for "no" option (default: "No")

  • :initial_value (Object)

    default selection (default: true); coerced to a Boolean, so nil and false start on "no" and any other value starts on "yes"

  • :vertical (Boolean)

    render the two options on separate lines instead of side by side (default: false); handy for long or localized labels

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Boolean, CANCEL)

    true/false or CANCEL if cancelled



238
239
240
# File 'lib/clack.rb', line 238

def confirm(message:, **opts)
  Prompts::Confirm.new(message:, **opts).run
end

.date(message:, **opts) ⇒ Date, CANCEL

Prompt for date selection with inline segmented input.

Navigate between segments with Tab/arrow keys, adjust with up/down, or type digits directly.

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :format (Symbol)

    date format (:iso, :us, :eu)

  • :initial_value (Date, Time, String, nil)

    initial date value (default: today)

  • :min (Date, nil)

    minimum allowed date

  • :max (Date, nil)

    maximum allowed date

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator (see Clack::Validators.resolve); a proc returns an error string, Warning, or nil; nil or false disables validation

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Date, CANCEL)

    selected date or CANCEL if cancelled



507
508
509
# File 'lib/clack.rb', line 507

def date(message:, **opts)
  Prompts::Date.new(message:, **opts).run
end

.demovoid

This method returns an undefined value.

Run the interactive demo showcasing all Clack features. The demo implementation is in examples/demo.rb.



670
671
672
673
674
# File 'lib/clack.rb', line 670

def demo
  demo_path = File.expand_path("../examples/demo.rb", __dir__)
  load demo_path
  run_demo
end

.group(on_cancel: nil) {|group| ... } ⇒ Hash, Clack::CANCEL

Run a group of prompts and collect their results.

If any prompt is cancelled, the entire group returns Clack::CANCEL. The on_cancel callback receives partial results collected so far.

Examples:

result = Clack.group do |g|
  g.prompt(:name) { Clack.text(message: "Name?") }
  g.prompt(:confirm) { Clack.confirm(message: "Continue?") }
end

if Clack.cancel?(result)
  Clack.cancel("Cancelled")
else
  puts "Name: #{result[:name]}"
end

Parameters:

  • on_cancel (Proc, nil) (defaults to: nil)

    Callback when a prompt is cancelled

Yields:

  • (group)

    Block to define prompts

Yield Parameters:

Returns:

Raises:

  • (ArgumentError)


92
93
94
95
96
97
98
# File 'lib/clack/group.rb', line 92

def group(on_cancel: nil, &block)
  raise ArgumentError, "Block required for Clack.group" unless block_given?

  group = Group.new(on_cancel: on_cancel)
  block.call(group)
  group.run
end

.group_multiselect(message:, options:, **opts) ⇒ Array, CANCEL

Prompt to select multiple options organized in groups.

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash>, Hash)

    groups with :label and :options, or a Hash of group label => options (each options list accepts an Array or a value => label Hash)

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :initial_values (Array, nil)

    initially selected values

  • :required (Boolean)

    require at least one selection (default: true)

  • :cursor_at (Object, nil)

    value of initially focused option

  • :selectable_groups (Boolean)

    allow toggling entire groups (default: false)

  • :group_spacing (Integer)

    lines between groups (default: 0)

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :show_instructions (Boolean, nil)

    show the keyboard hint footer (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Array, CANCEL)

    selected values or CANCEL if cancelled



487
488
489
# File 'lib/clack.rb', line 487

def group_multiselect(message:, options:, **opts)
  Prompts::GroupMultiselect.new(message:, options: options, **opts).run
end

.handle_cancel(value, message = nil, with_guide: nil, output: $stdout) ⇒ Boolean

Check if cancelled and show cancel message if so. Useful for guard clauses in CLI scripts.

Examples:

Guard clause pattern

name = Clack.text(message: "Name?")
return if Clack.handle_cancel(name)  # Shows "Cancelled" and returns true

With custom message

return if Clack.handle_cancel(name, "Aborted by user")

Parameters:

  • value (Object)

    the result from a prompt

  • message (String, nil) (defaults to: nil)

    message to display if cancelled (default: the global messages, "Cancelled"; see #update_settings)

  • with_guide (Boolean, nil) (defaults to: nil)

    show the guide symbol (default: Clack.settings)

  • output (IO) (defaults to: $stdout)

    output stream

Returns:

  • (Boolean)

    true if cancelled



118
119
120
121
122
123
# File 'lib/clack.rb', line 118

def handle_cancel(value, message = nil, with_guide: nil, output: $stdout)
  return false unless cancel?(value)

  cancel(message || Core::Settings.message(:cancel), with_guide:, output:)
  true
end

.intro(title = nil, with_guide: nil, output: $stdout) ⇒ void

This method returns an undefined value.

Display an intro banner at the start of a CLI session.

Parameters:

  • title (String, nil) (defaults to: nil)

    optional title text

  • with_guide (Boolean, nil) (defaults to: nil)

    show the guide symbol (default: Clack.settings)

  • output (IO) (defaults to: $stdout)

    output stream (default: $stdout)



131
132
133
134
# File 'lib/clack.rb', line 131

def intro(title = nil, with_guide: nil, output: $stdout)
  prefix = Core::Settings.with_guide?(with_guide) ? "#{Colors.gray(Symbols::S_BAR_START)}  " : ""
  output.puts "#{prefix}#{title}"
end

.logModule

Access the Log module for styled console output.

Returns:

  • (Module)

    the Log module



543
544
545
# File 'lib/clack.rb', line 543

def log
  Log
end

.multiline_text(message:, **opts) ⇒ String, CANCEL

Prompt for multi-line text input.

Enter inserts a newline, Ctrl+D submits. Useful for commit messages, notes, or any multi-line content.

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :initial_value (String, nil)

    pre-filled editable text (can contain newlines)

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator (see Clack::Validators.resolve); a proc returns an error string, Warning, or nil; nil or false disables validation

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (String, CANCEL)

    user input (lines joined with \n) or CANCEL if cancelled



199
200
201
# File 'lib/clack.rb', line 199

def multiline_text(message:, **opts)
  Prompts::MultilineText.new(message:, **opts).run
end

.multiselect(message:, options:, **opts) ⇒ Array, CANCEL

Prompt to select multiple options from a list.

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash, String>, Hash)

    list of options, or a Hash of value => label (or value => hint:, disabled:)

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :initial_values (Array, nil)

    initially selected values

  • :required (Boolean)

    require at least one selection (default: true)

  • :max_items (Integer, nil)

    max visible items (enables scrolling)

  • :cursor_at (Object, nil)

    value of initially focused option

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :show_instructions (Boolean, nil)

    show the keyboard hint footer (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Array, CANCEL)

    selected values or CANCEL if cancelled



274
275
276
# File 'lib/clack.rb', line 274

def multiselect(message:, options:, **opts)
  Prompts::Multiselect.new(message:, options: options, **opts).run
end

.note(message = "", title: nil, **opts) ⇒ void

This method returns an undefined value.

Display a note box with optional title.

Parameters:

  • message (String) (defaults to: "")

    the note content

  • title (String, nil) (defaults to: nil)

    optional title

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)



560
561
562
# File 'lib/clack.rb', line 560

def note(message = "", title: nil, **opts)
  Note.render(message, title: title, **opts)
end

.outro(message = nil, with_guide: nil, output: $stdout) ⇒ void

This method returns an undefined value.

Display an outro banner at the end of a CLI session.

Parameters:

  • message (String, nil) (defaults to: nil)

    optional closing message

  • with_guide (Boolean, nil) (defaults to: nil)

    show the guide symbol (default: Clack.settings)

  • output (IO) (defaults to: $stdout)

    output stream (default: $stdout)



142
143
144
145
146
147
148
149
150
# File 'lib/clack.rb', line 142

def outro(message = nil, with_guide: nil, output: $stdout)
  if Core::Settings.with_guide?(with_guide)
    output.puts Colors.gray(Symbols::S_BAR)
    output.puts "#{Colors.gray(Symbols::S_BAR_END)}  #{message}"
  else
    output.puts message.to_s
  end
  output.puts
end

.password(message:, **opts) ⇒ String, CANCEL

Prompt for password input (masked display).

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :mask (String)

    character to display for each input character (default: ▪)

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator (see Clack::Validators.resolve); a proc returns an error string, Warning, or nil; nil or false disables validation

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (String, CANCEL)

    password or CANCEL if cancelled



213
214
215
# File 'lib/clack.rb', line 213

def password(message:, **opts)
  Prompts::Password.new(message:, **opts).run
end

.path(message:, **opts) ⇒ String, CANCEL

Prompt for file/directory path with filesystem navigation.

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :root (String)

    starting directory (default: ".")

  • :only_directories (Boolean)

    only show directories (default: false)

  • :max_items (Integer, nil)

    max visible items (enables scrolling, default: 5)

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator for the resolved absolute path (see Clack::Validators.resolve); :directory_exists and :path_exists fit here

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :show_instructions (Boolean, nil)

    show the keyboard hint footer (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (String, CANCEL)

    selected path or CANCEL if cancelled



408
409
410
# File 'lib/clack.rb', line 408

def path(message:, **opts)
  Prompts::Path.new(message:, **opts).run
end

.progress(total:, **opts) ⇒ Prompts::Progress

Create a progress bar for measurable operations.

Parameters:

  • total (Integer)

    total number of steps

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :message (String, nil)

    optional message

Returns:



417
418
419
# File 'lib/clack.rb', line 417

def progress(total:, **opts)
  Prompts::Progress.new(total: total, **opts)
end

.range(message:, **opts) ⇒ Numeric, CANCEL

Prompt for a numeric value using a slider.

Navigate with left/right or up/down arrow keys. Press Enter to confirm.

Examples:

Basic usage

volume = Clack.range(message: "Volume", min: 0, max: 100, step: 5)

Fractional step

opacity = Clack.range(message: "Opacity", min: 0, max: 1, step: 0.1)
# => 0.3 after three right arrows

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :min (Numeric)

    minimum value (default: 0)

  • :max (Numeric)

    maximum value (default: 100)

  • :step (Numeric)

    increment size (default: 1); fractional steps such as 0.1 are snapped exactly, so three steps from 0 is 0.3

  • :initial_value (Numeric, nil)

    initial value (defaults to min)

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator (see Clack::Validators.resolve); a proc returns an error string, Warning, or nil; nil or false disables validation

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Numeric, CANCEL)

    the selected value (Integer when min and step are both Integers, Float when either is a Float; Rational inputs return Rational) or CANCEL if cancelled



536
537
538
# File 'lib/clack.rb', line 536

def range(message:, **opts)
  Prompts::Range.new(message:, **opts).run
end

.rows(output = $stdout, default: 24) ⇒ Integer

Get terminal rows (height)

Parameters:

  • output (IO) (defaults to: $stdout)

    Output stream

  • default (Integer) (defaults to: 24)

    Default if detection fails

Returns:

  • (Integer)


662
663
664
# File 'lib/clack.rb', line 662

def rows(output = $stdout, default: 24)
  Environment.rows(output, default: default)
end

.select(message:, options:, **opts) ⇒ Object, CANCEL

Prompt to select one option from a list.

Examples:

Hash shorthand

db = Clack.select(message: "Database?", options: {pg: "PostgreSQL", mysql: "MySQL"})
# => :pg

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash, String>, Hash)

    list of options, or a Hash of value => label (or value => hint:, disabled:); see README "Option shorthands"

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :initial_value (Object, nil)

    value of initially selected option

  • :max_items (Integer, nil)

    max visible items (enables scrolling)

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :show_instructions (Boolean, nil)

    show the keyboard hint footer (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Object, CANCEL)

    selected value or CANCEL if cancelled



257
258
259
# File 'lib/clack.rb', line 257

def select(message:, options:, **opts)
  Prompts::Select.new(message:, options: options, **opts).run
end

.select_key(message:, options:, **opts) ⇒ Object, CANCEL

Prompt to select an option by pressing a key.

Each option carries a single-character :key (defaults to the first character of the value). Pressing that key selects the option and submits immediately, so there is no cursor to move. Enter only does something when :initial_value highlights a default. Option keys win over custom key aliases (except aliases mapped to :cancel).

Examples:

Distinct upper- and lowercase keys with a safe default

Clack.select_key(
  message: "Apply migration?",
  options: [
    { value: :yes_all, label: "Yes to all", key: "Y" },
    { value: :yes, label: "Yes", key: "y" },
    { value: :no, label: "No", key: "n", hint: "default" }
  ],
  case_sensitive: true,
  initial_value: :no
)

Hash shorthand

Clack.select_key(message: "Action?", options: {create: "Create", open: "Open", quit: "Quit"})
# press "o" => :open

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash>, Hash)

    options with :value, :label, and optionally :key and :hint, or a Hash of value => label (key defaults to the first character of the value) or value => key:, hint:

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :case_sensitive (Boolean)

    match keys exactly instead of ignoring case (default: false)

  • :initial_value (Object, nil)

    value of the option highlighted at start; Enter submits it and CI mode returns it (default: nil). The highlight is a color effect, so when colors are off (NO_COLOR, piped output) mark the default in that option's :hint. A value that matches no option is ignored with a warning on stderr

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator (see Clack::Validators.resolve); a proc returns an error string, Warning, or nil; nil or false disables validation

  • :transform (Symbol, Proc, nil)

    transform function to normalize the value

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (Object, CANCEL)

    selected value or CANCEL if cancelled



460
461
462
# File 'lib/clack.rb', line 460

def select_key(message:, options:, **opts)
  Prompts::SelectKey.new(message:, options: options, **opts).run
end

.settingsHash

Access global settings

Returns:

  • (Hash)

    Current configuration (:aliases, :with_guide, :show_instructions, :ci_mode, :messages)

See Also:



593
594
595
# File 'lib/clack.rb', line 593

def settings
  Core::Settings.config
end

.setup!void

This method returns an undefined value.

Install signal handlers for clean terminal cleanup. Call this once in your CLI entry point. Handles INT, TERM, and SIGWINCH. Without calling this, Ctrl+C may leave the cursor hidden.



681
682
683
684
685
686
687
688
# File 'lib/clack.rb', line 681

def setup!
  return if @setup_done

  @setup_done = true
  install_signal_handlers
  install_at_exit
  Core::Prompt.setup_signal_handler
end

.setup?Boolean

Returns whether setup! has been called.

Returns:

  • (Boolean)

    whether setup! has been called



691
# File 'lib/clack.rb', line 691

def setup? = !!@setup_done

.spin(message, success: nil, error: nil, **opts) ⇒ Object

Run a block with a spinner, handling success/error automatically.

If the block does not complete, the spinner still ends with a final line before the exception or non-local exit propagates: the cancel message for exit (any status), Ctrl+C, break, and throw; error or the exception message for anything raised.

Examples:

Basic usage

result = Clack.spin("Installing dependencies...") { system("npm install") }

With custom success message

Clack.spin("Compiling...", success: "Build complete!") { build_project }

Access spinner inside block

Clack.spin("Working...") do |s|
  s.message "Step 1..."
  do_step_1
  s.message "Step 2..."
  do_step_2
end

Early exit still prints a final line

Clack.spin("Building", cancel_message: "Build cancelled") { exit 2 }
# => "■  Build cancelled", then the process exits with status 2

Parameters:

  • message (String)

    initial spinner message

  • success (String, nil) (defaults to: nil)

    message on success (defaults to message)

  • error (String, nil) (defaults to: nil)

    message on error (defaults to exception message)

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :cancel_message (String, nil)

    see #spinner

  • :error_message (String, nil)

    see #spinner; note that an exception raised by the block uses error: or the exception message, not this

  • :on_cancel (#call, nil)

    see #spinner

  • :with_guide (Boolean, nil)

    see #spinner

Returns:

  • (Object)

    the block's return value

Raises:

  • (Exception)

    re-raises any exception from the block



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/clack.rb', line 340

def spin(message, success: nil, error: nil, **opts)
  s = spinner(**opts)
  s.start(message)
  begin
    result = yield(s)
    s.stop(success || message)
    result
  rescue SystemExit, SignalException
    s.cancel
    raise
  rescue Exception => exception # standard:disable Lint/RescueException
    s.error(error || exception.message)
    raise
  ensure
    # break or throw out of the block leave no exception in flight; a
    # no-op when one of the clauses above already finished the spinner.
    s.abandon
  end
end

.spinner(**opts) ⇒ Prompts::Spinner

Create an animated spinner for async operations.

Examples:

Custom cancel and error messages

s = Clack.spinner(cancel_message: "Deploy aborted", error_message: "Deploy failed",
                  on_cancel: -> { release_lock })
s.start("Deploying")

Parameters:

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :indicator (:dots, :timer)

    animation style (default: :dots)

  • :frames (Array<String>, nil)

    custom animation frames

  • :delay (Float, nil)

    seconds between frames

  • :style_frame (Proc, nil)

    proc to style each frame

  • :cancel_message (String, nil)

    text for #cancel with no argument and for Ctrl+C / exit while running (default: the global messages, "Cancelled")

  • :error_message (String, nil)

    text for #error with no argument and for an uncaught exception while running (default: the global messages, "Something went wrong")

  • :on_cancel (#call, nil)

    called with no arguments after the spinner is cancelled, whether by #cancel, Ctrl+C, exit, or an early exit from a Clack.spin block; a StandardError raised by the hook is reported with Kernel#warn and swallowed

  • :output (IO)

    output stream (default: $stdout)

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

Returns:

  • (Prompts::Spinner)

    spinner instance (call #start, #stop, #error, #cancel, #clear)

Raises:

  • (ArgumentError)

    if cancel_message/error_message are not Strings or on_cancel does not respond to #call



302
303
304
# File 'lib/clack.rb', line 302

def spinner(**opts)
  Prompts::Spinner.new(**opts)
end

.streamModule

Access the Stream module for streaming output.

Returns:

  • (Module)

    the Stream module



550
551
552
# File 'lib/clack.rb', line 550

def stream
  Stream
end

.task_log(title:, **opts) ⇒ TaskLog

Create a streaming task log that clears on success, shows on error. Useful for build output, npm install style streaming, etc.

Parameters:

  • title (String)

    title displayed at the top

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :limit (Integer, nil)

    max lines to show (older lines scroll out)

  • :retain_log (Boolean)

    keep full log history for display on error

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

Returns:



586
587
588
# File 'lib/clack.rb', line 586

def task_log(title:, **opts)
  TaskLog.new(title: title, **opts)
end

.tasks(tasks:, **opts) ⇒ Array<Hash>

Run multiple tasks with progress indicators.

Parameters:

  • tasks (Array<Hash>)

    tasks with :title, :task (Proc), and optional :enabled (Boolean, default: true)

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

Returns:

  • (Array<Hash>)

    task results



469
470
471
# File 'lib/clack.rb', line 469

def tasks(tasks:, **opts)
  Prompts::Tasks.new(tasks: tasks, **opts).run
end

.text(message:, **opts) ⇒ String, CANCEL

Prompt for single-line text input.

Parameters:

  • message (String)

    the prompt message

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :placeholder (String, nil)

    dim text shown when input is empty

  • :default_value (String, nil)

    value used if submitted empty

  • :initial_value (String, nil)

    pre-filled editable text

  • :completions (Array<String>, Proc, nil)

    tab completion candidates (array or proc)

  • :validate (Proc, Regexp, Symbol, Array, Hash, nil, false)

    validator (see Clack::Validators.resolve); a proc returns an error string, Warning, or nil; nil or false disables validation

  • :transform (Symbol, Proc, nil)

    transform function to normalize the value

  • :help (String, nil)

    help text shown below the message

  • :with_guide (Boolean, nil)

    show the guide rail (default: Clack.settings)

  • :instructions (String, Array<String>, nil)

    custom keyboard hint footer text, rendered verbatim on one line (newlines are not re-prefixed)

Returns:

  • (String, CANCEL)

    user input or CANCEL if cancelled



182
183
184
# File 'lib/clack.rb', line 182

def text(message:, **opts)
  Prompts::Text.new(message:, **opts).run
end

.tty?(output = $stdout) ⇒ Boolean

Check if stdout is a TTY

Parameters:

  • output (IO) (defaults to: $stdout)

    Output stream to check

Returns:

  • (Boolean)


646
647
648
# File 'lib/clack.rb', line 646

def tty?(output = $stdout)
  Environment.tty?(output)
end

.update_settings(**opts) ⇒ Hash

Update global settings

Examples:

Custom key bindings

Clack.update_settings(aliases: { "y" => :enter, "n" => :cancel })

Disable guide bars everywhere (per-call with_guide: overrides this)

Clack.update_settings(with_guide: false)

Hide keyboard hint footers

Clack.update_settings(show_instructions: false)

Enable CI mode (auto-submit with defaults)

Clack.update_settings(ci_mode: true)

Auto-detect CI mode (piped input or CI environment)

# Without this, prompting on a piped stdin raises Clack::NotATerminalError.
Clack.update_settings(ci_mode: :auto)

Localize cancel and error messages

Clack.update_settings(messages: {cancel: "Abgebrochen", error: "Etwas ging schief"})

Parameters:

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :aliases (Hash, nil)

    Custom key to action mappings

  • :with_guide (Boolean, nil)

    Whether to show guide bars (the gray rail and corners around prompts)

  • :show_instructions (Boolean, nil)

    Whether list prompts show their keyboard hint footer

  • :ci_mode (Boolean, Symbol, nil)

    CI mode: true (always), :auto (active when the prompt's input is not a TTY, or a CI env var is set), false (never)

  • :messages (Hash{Symbol=>String}, nil)

    Cancel/error strings used by spinners and #handle_cancel: {cancel: "Cancelled", error: "Something went wrong"}. Keys are merged, so either can be given alone.

Returns:

  • (Hash)

    Updated configuration

Raises:

  • (ArgumentError)

    for an unknown messages key or a non-String value



627
628
629
# File 'lib/clack.rb', line 627

def update_settings(**opts)
  Core::Settings.update(**opts)
end

.warning(message) ⇒ Warning

Create a validation warning that allows the user to proceed with confirmation.

Examples:

validate: ->(v) { Clack.warning("Unusual value") if v.length > 100 }

Parameters:

  • message (String)

    the warning message

Returns:



86
87
88
# File 'lib/clack.rb', line 86

def warning(message)
  Warning.new(message)
end

.windows?Boolean

Check if running on Windows

Returns:

  • (Boolean)


639
640
641
# File 'lib/clack.rb', line 639

def windows?
  Environment.windows?
end