Module: Recourse::Helpers::Constraints

Included in:
Recourse::Helpers
Defined in:
lib/recourse/helpers/constraints.rb

Overview

Turns a model's validators into the HTML that constrains a form field.

Constant Summary collapse

SAMPLE_PLACEHOLDERS =

Shown for a field whose shape has one canonical example.

{ 'phone' => '555-555-5555', 'email' => 'michael@example.com' }.freeze
DISPLAY_PATTERNS =

What the browser checks where the typed shape differs from the stored one: a phone is ten digits in the database but is typed with its separators.

{ 'phone' => '[2-9]\d{2}-[2-9]\d{2}-\d{4}' }.freeze
PHONE_CONTROLLER =

Hands a phone field to the Stimulus controller that types its separators.

{
  controller: 'phone', action: 'keydown->phone#down input->phone#input',
}.freeze

Instance Method Summary collapse

Instance Method Details

#field_html(column, type = nil, model = resource_model) ⇒ Object

Browser-side constraints, every one read from the validators of model — which is the page's model unless a field asks about another one's attribute.



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/recourse/helpers/constraints.rb', line 19

def field_html(column, type = nil, model = resource_model)
  key = (type || column).to_s
  pattern = DISPLAY_PATTERNS[key] || column_pattern(model, column)

  {
    maxlength: length_option(model, column, :maximum),
    minlength: length_option(model, column, :minimum), pattern:,
    title: title(key, pattern), placeholder: placeholder(model, column, type),
    inputmode: (:numeric if numeric? model, column, pattern),
    required: (true if required? model, column),
    data: (PHONE_CONTROLLER if key == 'phone'),
  }.compact
end