class BaseForm::Form

This class is the main core functionality, by being an inheritable class, which controls the form attributes assignments, validations and persisting.

Basically you should create your own Form Object Class, and inherit this class (BaseForm::Form). After that you should put all records in the `@form_records` variable, through `use_form_records` class method. In your `persist` method implementation, just create the record objects associating it to each variable in `form_records.`

Attributes

form_records[R]

Public Class Methods

save(*params) click to toggle source
# File lib/base_form/form.rb, line 29
def self.save(*params)
  new(*params).save
end

Protected Class Methods

use_form_records(*records) click to toggle source
# File lib/base_form/form.rb, line 22
def use_form_records(*records)
  attr_reader(*records)

  @form_records = records
end

Public Instance Methods

persisted?() click to toggle source
# File lib/base_form/form.rb, line 49
def persisted?
  @persisted
end
save() click to toggle source

This method will make the things happen. It'll try run validations set in your form class, and if it passes, it'll run your persist instructions in a block of ActiveRecord transaction. If some record fails it's persistence/validation, then a rollback will be raised, the form will return those errors grouped in it. Otherwise everything is commited and `persisted?` method will return true.

# File lib/base_form/form.rb, line 39
def save
  perform_in_transaction { persist } if valid?

  self
end
valid?() click to toggle source
Calls superclass method
# File lib/base_form/form.rb, line 45
def valid?
  errors.empty? && super
end

Protected Instance Methods

add_errors_for(error) click to toggle source
# File lib/base_form/form.rb, line 76
def add_errors_for(error)
  error.each do |attribute, message|
    errors.add attribute, message
  end
end
perform_in_transaction() { || ... } click to toggle source
# File lib/base_form/form.rb, line 59
def perform_in_transaction
  ActiveRecord::Base.transaction do
    yield if block_given?

    records_errors.each { |error| add_errors_for(error) }
    raise ActiveRecord::Rollback if errors.any?

    @persisted = true
  end
end
persist() click to toggle source
# File lib/base_form/form.rb, line 55
def persist
  raise NotImplementedError
end
records_errors() click to toggle source
# File lib/base_form/form.rb, line 70
def records_errors
  self.class.form_records.map do |form_record|
    send(form_record).try(:errors)
  end.compact.flatten
end