Class: Formulario::Form
- Inherits:
-
Object
- Object
- Formulario::Form
- Defined in:
- lib/formulario/form.rb
Instance Attribute Summary collapse
-
#model ⇒ Object
Returns the value of attribute model.
Class Method Summary collapse
Instance Method Summary collapse
- #error_fields ⇒ Object
- #errors ⇒ Object
- #fields ⇒ Object
-
#initialize(skip_validations: false, **params) ⇒ Form
constructor
A new instance of Form.
- #on_invalid ⇒ Object
- #on_valid ⇒ Object
- #params ⇒ Object
- #valid? ⇒ Boolean
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, **| 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
#model ⇒ Object
Returns the value of attribute model.
3 4 5 |
# File 'lib/formulario/form.rb', line 3 def model @model end |
Class Method Details
.default ⇒ Object
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_fields ⇒ Object
59 60 61 |
# File 'lib/formulario/form.rb', line 59 def error_fields @error_fields ||= fields.select { |_, field| field.exceptional? } end |
#errors ⇒ Object
63 64 65 |
# File 'lib/formulario/form.rb', line 63 def errors error_fields.transform_values(&:to_a) end |
#fields ⇒ Object
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_invalid ⇒ Object
72 73 74 75 |
# File 'lib/formulario/form.rb', line 72 def on_invalid yield unless valid? self end |
#on_valid ⇒ Object
67 68 69 70 |
# File 'lib/formulario/form.rb', line 67 def on_valid yield if valid? self end |
#params ⇒ Object
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 = field_info.last res[field_name] = .value.value } end |
#valid? ⇒ Boolean
55 56 57 |
# File 'lib/formulario/form.rb', line 55 def valid? __fields.none? { |_, field| field.value.exceptional? } end |