Module: Clack::Core::SelectionManager
- Defined in:
- lib/clack/core/selection_manager.rb
Overview
Shared selection management for multi-select prompts. Handles toggle, toggle-all, required validation, and value tracking.
Including classes must define:
-
@selected [Set] the set of selected values
-
@required [Boolean] whether at least one selection is required
Constant Summary collapse
- REQUIRED_ERROR =
"Please select at least one option. Press %s to select, %s to submit"
Instance Method Summary collapse
-
#resolve_initial_selection(initial_values, valid_values) ⇒ Set
Resolve requested pre-selections against the selectable option values.
-
#selected_labels(all_options) ⇒ String
Build the final display string from selected options.
-
#toggle_value(value) ⇒ Object
Toggle a value in the selection set.
-
#update_selection_value ⇒ Object
Update @value from the current selection.
-
#validate_selection ⇒ Boolean
Validate that selection meets requirements before submit.
Instance Method Details
#resolve_initial_selection(initial_values, valid_values) ⇒ Set
Resolve requested pre-selections against the selectable option values.
Values that don’t match any current option are dropped and reported on stderr, since they’re almost always a typo in initial_values rather than an intentional no-op.
23 24 25 26 27 28 29 30 |
# File 'lib/clack/core/selection_manager.rb', line 23 def resolve_initial_selection(initial_values, valid_values) requested = Set.new(initial_values) unknown = requested - valid_values unless unknown.empty? warn "[clack] ignoring unknown initial_values: #{unknown.to_a.inspect}" end requested & valid_values end |
#selected_labels(all_options) ⇒ String
Build the final display string from selected options.
62 63 64 |
# File 'lib/clack/core/selection_manager.rb', line 62 def selected_labels() .select { |o| @selected.include?(o.value) }.map { |o| o.label }.join(", ") end |
#toggle_value(value) ⇒ Object
Toggle a value in the selection set.
34 35 36 37 38 39 40 |
# File 'lib/clack/core/selection_manager.rb', line 34 def toggle_value(value) if @selected.include?(value) @selected.delete(value) else @selected.add(value) end end |
#update_selection_value ⇒ Object
Update @value from the current selection.
55 56 57 |
# File 'lib/clack/core/selection_manager.rb', line 55 def update_selection_value @value = @selected.to_a end |
#validate_selection ⇒ Boolean
Validate that selection meets requirements before submit. Sets error state if required and empty.
45 46 47 48 49 50 51 52 |
# File 'lib/clack/core/selection_manager.rb', line 45 def validate_selection if @required && @selected.empty? @error_message = format(REQUIRED_ERROR, Colors.cyan("space"), Colors.cyan("enter")) @state = :error return false end true end |