Class: FlowChat::Prompt

Inherits:
Object
  • Object
show all
Defined in:
lib/flow_chat/prompt.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Prompt

Returns a new instance of Prompt.



5
6
7
# File 'lib/flow_chat/prompt.rb', line 5

def initialize(input)
  @user_input = input
end

Instance Attribute Details

#user_inputObject (readonly)

Returns the value of attribute user_input.



3
4
5
# File 'lib/flow_chat/prompt.rb', line 3

def user_input
  @user_input
end

Instance Method Details

#ask(msg, choices: nil, transform: nil, validate: nil, media: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/flow_chat/prompt.rb', line 9

def ask(msg, choices: nil, transform: nil, validate: nil, media: nil)
  if user_input.present?
    input = user_input
    validation_error = validate.call(input) if validate.present?

    if validation_error.present?
      # Use config to determine whether to combine validation error with original message
      message = if FlowChat::Config.combine_validation_error_with_message
        [validation_error, msg].join("\n\n")
      else
        validation_error
      end
      prompt!(message, choices: choices, media: media)
    end

    input = transform.call(input) if transform.present?
    return input
  end

  # Pass raw message and media separately to the renderer
  prompt! msg, choices: choices, media: media
end

#say(message, media: nil) ⇒ Object



32
33
34
35
# File 'lib/flow_chat/prompt.rb', line 32

def say(message, media: nil)
  # Pass raw message and media separately to the renderer
  terminate! message, media: media
end

#select(msg, choices, media: nil, error_message: "Invalid selection:") ⇒ Object

Raises:

  • (ArgumentError)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/flow_chat/prompt.rb', line 37

def select(msg, choices, media: nil, error_message: "Invalid selection:")
  raise ArgumentError, "choices must be an array or hash" unless choices.is_a?(Array) || choices.is_a?(Hash)

  normalized_choices = normalize_choices(choices)
  ask(
    msg,
    choices: choices,
    validate: lambda { |choice| error_message unless normalized_choices.key?(choice.to_s) },
    transform: lambda do |choice|
      choices = choices.keys if choices.is_a?(Hash)
      choices.index_by { |choice| choice.to_s }[choice.to_s]
    end,
    media: media
  )
end

#yes?(msg) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/flow_chat/prompt.rb', line 53

def yes?(msg)
  select(msg, ["Yes", "No"]) == "Yes"
end