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
8
9
10
# File 'lib/flow_chat/prompt.rb', line 5

def initialize(input)
  # Always work with a FlowChat::Input so `submitted?` (text OR attachment)
  # gates the turn, and validate/transform receive the rich turn. A bare
  # string (or nil) is wrapped as text.
  @user_input = input.is_a?(FlowChat::Input) ? input : FlowChat::Input.new(text: 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



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

def ask(msg, choices: nil, transform: nil, validate: nil, media: nil)
  if user_input.
    validation_error = validate.call(user_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

    return transform.present? ? transform.call(user_input) : user_input.to_s
  end

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

#say(message, media: nil) ⇒ Object



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

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)


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

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)


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

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