Class: Formulario::Form

Inherits:
Object
  • Object
show all
Defined in:
lib/formulario/form.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(skip_validations: false, **params) ⇒ Form

Returns a new instance of Form.



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/formulario/form.rb', line 5

def initialize(skip_validations: false, **params)
  self.class.__fields.each do |field_name, **options|
    send("#{field_name}=", params.delete(field_name))
  end

  params.each do |k, v|
    if self.respond_to?("#{k}=")
      send("#{k}=", v)
    end
  end

  __validate! unless skip_validations
end

Instance Attribute Details

#modelObject

Returns the value of attribute model.



3
4
5
# File 'lib/formulario/form.rb', line 3

def model
  @model
end

Class Method Details

.defaultObject



31
32
33
34
35
36
37
38
# File 'lib/formulario/form.rb', line 31

def self.default
  params = __fields.each_with_object({}) { |field, res|
    default_value    = field.last.default
    res[field.first] = default_value.is_a?(Proc) ? nil : default_value
  }

  new(skip_validations: true, **params)
end

.for(model, **rest) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/formulario/form.rb', line 19

def self.for(model, **rest)
  if model
    fields = __fields.keys.each_with_object({}) { |field_name, res|
      res[field_name] = model.send(field_name)
    }

    new(**fields.merge({model: model, **rest}))
  else
    new(**rest)
  end
end

Instance Method Details

#error_fieldsObject



59
60
61
# File 'lib/formulario/form.rb', line 59

def error_fields
  @error_fields ||= fields.select { |_, field| field.exceptional? }
end

#errorsObject



63
64
65
# File 'lib/formulario/form.rb', line 63

def errors
  error_fields.transform_values(&:to_a)
end

#fieldsObject



49
50
51
52
53
# File 'lib/formulario/form.rb', line 49

def fields
  @fields ||= __fields.each_with_object({}) { |field, result|
    result[field.first] = field.last.value
  }
end

#on_invalidObject



72
73
74
75
# File 'lib/formulario/form.rb', line 72

def on_invalid
  yield unless valid?
  self
end

#on_validObject



67
68
69
70
# File 'lib/formulario/form.rb', line 67

def on_valid
  yield if valid?
  self
end

#paramsObject



40
41
42
43
44
45
46
47
# File 'lib/formulario/form.rb', line 40

def params
  __fields.each_with_object({}) { |field_info, res|
    field_name = field_info.first
    options    = field_info.last

    res[field_name] = options.value.value
  }
end

#valid?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/formulario/form.rb', line 55

def valid?
  __fields.none? { |_, field| field.value.exceptional? }
end