Class: UI::InputOtpComponent

Inherits:
ViewComponent::Base
  • Object
show all
Includes:
InputOtpBehavior
Defined in:
app/view_components/ui/input_otp_component.rb

Overview

InputOtpComponent - ViewComponent implementation

Accessible one-time password container component. Supports both composition (with Group/Slot/Separator) and auto-generation.

Examples:

With composition

<%= render UI::InputOtpComponent.new(length: 6) do %>
  <%= render UI::InputOtpGroupComponent.new do %>
    <%= render UI::InputOtpSlotComponent.new(index: 0) %>
  <% end %>
<% end %>

Auto-generated

<%= render UI::InputOtpComponent.new(length: 6) %>

Instance Method Summary collapse

Methods included from InputOtpBehavior

#input_otp_classes, #input_otp_data_attributes, #input_otp_html_attributes

Constructor Details

#initialize(length: 6, pattern: "\\d", name: nil, id: nil, disabled: false, classes: "", **attributes) ⇒ InputOtpComponent

Returns a new instance of InputOtpComponent.

Parameters:

  • length (Integer) (defaults to: 6)

    Maximum number of OTP characters

  • pattern (String) (defaults to: "\\d")

    Regex pattern for valid characters (default: digits only)

  • name (String) (defaults to: nil)

    Form input name

  • id (String) (defaults to: nil)

    HTML id attribute

  • disabled (Boolean) (defaults to: false)

    Whether inputs are disabled

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

    Additional CSS classes

  • attributes (Hash)

    Additional HTML attributes



27
28
29
30
31
32
33
34
35
# File 'app/view_components/ui/input_otp_component.rb', line 27

def initialize(length: 6, pattern: "\\d", name: nil, id: nil, disabled: false, classes: "", **attributes)
  @length = length
  @pattern = pattern
  @name = name
  @id = id
  @disabled = disabled
  @classes = classes
  @attributes = attributes
end

Instance Method Details

#callObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/view_components/ui/input_otp_component.rb', line 37

def call
  attrs = input_otp_html_attributes
  attrs[:data] = attrs[:data].merge(@attributes.fetch(:data, {}))

   :div, **attrs.merge(@attributes.except(:data)) do
    if content.present?
      content
    else
      # Auto-generate inputs wrapped in InputOtpGroupComponent
      render(UI::InputOtpGroupComponent.new) do
        safe_join(
          @length.times.map do |i|
            render(UI::InputOtpSlotComponent.new(
              index: i,
              name: @name ? "#{@name}[#{i}]" : nil,
              id: @id ? "#{@id}_#{i}" : nil,
              disabled: @disabled
            ))
          end
        )
      end
    end
  end
end