Dev Thoughts

Musings from my development journey.

Topics

Decouple Your Models with Form Objects

large

Talk given by Andrew Markle.

Form Object

Definition

An object that can be passed into a form.

Typically added to a new directory called app/forms.

Benefits:

  • Not limited to ActiveRecord objects
  • Model agnostic

Challenges with Multi Page Forms

Working with Nested Attributes, managing data between sessions, and implementing validations from multiple models.

Sample form object, written from scratch:

class CompanyForm
  include ActiveModel::Model

  attr_accessor :name, :email, :etc

  def company
    @company ||= Company.new(name: name)
  end

  # Validations
  # Virtual attributes
  # Delegates
end

Alternate: Reform Gem

class AlbumForm < Reform::Form
  property :title
  validates :title, presence: true

  property :artist do
    property :full_name
    validates :full_name, presence: true
  end

  collection :songs do
    property :name
  end
end

Prepopulators vs Populators

The Reform gem includes the concept of prepopulators and populators, the easiest way to understand it is:

  • prepopulators work like Rails new and edit
  • populators work like Rails create and update

Advantages

  • Focused approach to building forms
  • Integrate validations in the form object instead of the model itself
  • Easier to manage multiple data relationships per form
  • Straightforward to test with tools such as Capybara
  • RESTful
  • Easier to extend and modify in the future
  • Can be integrated when needed