Class: Clarc::FormBase
- Inherits:
-
Object
- Object
- Clarc::FormBase
- Defined in:
- lib/clarc/form_base.rb
Instance Method Summary collapse
-
#initialize(params) ⇒ FormBase
constructor
A new instance of FormBase.
- #persist! ⇒ Object
- #to_hash ⇒ Object
- #valid? ⇒ Boolean
- #validators ⇒ Object
Constructor Details
#initialize(params) ⇒ FormBase
Returns a new instance of FormBase.
8 9 10 11 |
# File 'lib/clarc/form_base.rb', line 8 def initialize params @params = params build end |
Instance Method Details
#persist! ⇒ Object
47 48 49 50 51 52 53 |
# File 'lib/clarc/form_base.rb', line 47 def persist! validators.each do |attr, _| model_name = attr.to_s.camelize repository = "#{model_name}Repository".constantize repository.save(send(attr)) end end |
#to_hash ⇒ Object
41 42 43 44 45 |
# File 'lib/clarc/form_base.rb', line 41 def to_hash result = { errors: @errors } validators.each{ |attr, _| result[attr] = send(attr) } result end |
#valid? ⇒ Boolean
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/clarc/form_base.rb', line 17 def valid? @errors = {} valid = true validators.each do |attr, klass| value = send(attr) if value.is_a?(Array) value.each_with_index do |value, i| validator = klass.new(value) valid &= validator.valid? @errors[attr] ||= {} @errors[attr][i] = validator.errors end else validator = klass.new(value) valid &= validator.valid? @errors[attr] = validator.errors end end valid end |
#validators ⇒ Object
13 14 15 |
# File 'lib/clarc/form_base.rb', line 13 def validators {} end |