Input attributes from validators

Gem Version

Скачен 371 раз

Что оно делает

HTML inputs have powerful controls over browser via attributes:

Normally you write those HTML attributes manually or forget about them, but most of them can be inferred from model validations and the DB column name.

Как оно это делает

Provided that you have validators on your model:

class Review < ActiveRecord::Base

  validates :comment, presence: true, length: { min: 3, max: 1_000 }
  validates :score, numericality: { only_integer: true, in: 1..5 }
end

Individual helper methods

This gem exposes a set of helper methods, one for the corresponding HTML attribute:

validated_inputmode @rating, :comment #=> "text"
validated_minlength @review, :comment #=> 3
validated_maxlength @review, :comment #=> 1_000
validated_required  @review, :comment #=> true
validated_inputmode @rating, :score   #=> "numeric"
validated_min       @rating, :score   #=> 1
validated_max       @rating, :score   #=> 5
validated_step      @rating, :score   #=> 1

Aggregate method

There is also a method that returns a hash with all the values:

resolved_input_attributes(record, attribute_name) #=>
{
  inputmode:  <String || NilClass>,,
  max:       <Integer || NilClass>,
  maxlength: <Integer || NilClass>,
  min:       <Integer || NilClass>,
  minlength: <Integer || NilClass>,
  required: <Boolean>,
  step:      <Integer || Decimal>,
}

so you don’t have to repeadedly pass the record and the attribute name:

= form_for model: @review do |f|
  — attrs = resolved_input_attributes(@review, :score)

  = f.number_field :size \
                    inputmode: attrs[:inputmode], \
                    max:       attrs[:max], \
                    min:       attrs[:min], \
                    required:  attrs[:required], \
                    step:      attrs[:step]

  = f.text_field :description \
                    inputmode: attrs[:inputmode], \
                    maxlength: attrs[:maxlength], \
                    minlength: attrs[:minlength], \
                    required:  attrs[:required]

Ссылки