Class: FlowChat::Whatsapp::IdGenerator

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

Overview

Generates WhatsApp-safe IDs from choice labels

WhatsApp Cloud API requires button and list item IDs to be:

  • Maximum 256 characters
  • Unique within the message
  • Non-empty strings

This generator:

  • Sanitizes labels to alphanumeric + underscore/hyphen
  • Truncates to fit within 256-char limit
  • Appends hash suffix for duplicate labels (similar to Rails index naming)
  • Ensures readability while maintaining uniqueness

Examples:

Basic usage

generator = IdGenerator.new
id = generator.generate_id("Create Account")  # => "create_account"

Handling duplicates

generator = IdGenerator.new
id1 = generator.generate_id("Accept")  # => "accept"
id2 = generator.generate_id("Accept")  # => "accept_a1b2c3"

Special characters

generator = IdGenerator.new
id = generator.generate_id("Yes! 👍 (recommended)")  # => "yes_recommended"

Constant Summary collapse

MAX_ID_LENGTH =
256
HASH_SUFFIX_LENGTH =
3

Instance Method Summary collapse

Constructor Details

#initializeIdGenerator

Returns a new instance of IdGenerator.



35
36
37
# File 'lib/flow_chat/whatsapp/id_generator.rb', line 35

def initialize
  @generated_ids = []
end

Instance Method Details

#generate_id(label) ⇒ String

Generate a WhatsApp-safe ID from a label

Parameters:

  • label (String)

    The choice label to convert

Returns:

  • (String)

    A sanitized, unique ID



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/flow_chat/whatsapp/id_generator.rb', line 43

def generate_id(label)
  # Normalize the label
  normalized = normalize_label(label)

  # If normalized label is empty, use a fallback
  normalized = "choice" if normalized.empty?

  # Truncate to limit first
  truncated = truncate_to_limit(normalized)

  # Check if we need a hash suffix for uniqueness
  final_id = if @generated_ids.include?(truncated)
    add_hash_suffix(truncated, label)
  else
    truncated
  end

  # Track this ID
  @generated_ids << final_id

  final_id
end

#generated_idsObject

Get all generated IDs (useful for debugging)



72
73
74
# File 'lib/flow_chat/whatsapp/id_generator.rb', line 72

def generated_ids
  @generated_ids.dup
end

#resetObject

Reset the generator state (useful for testing or starting a new message)



67
68
69
# File 'lib/flow_chat/whatsapp/id_generator.rb', line 67

def reset
  @generated_ids = []
end