Class: Conformista::FormObject

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Callbacks, Presenting
Includes:
ActiveModel::Model, ActiveModel::Validations::Callbacks, Transactions, Validations
Defined in:
lib/conformista/form_object.rb

Overview

The FormObject is an ActiveModel-compliant object that knows how to present multiple Ruby objects (usually descendents of ActiveRecord::Base) to the view layer in an application. The form object is specifically designed to work with Rails form_for helpers.

The form object's responsibility is not too complex:

  • Provide accessors to presented models.
  • Delegate selected attributes on the form object to the appropriate presented models.
  • Delegate model validation and persistence.

We can make the behaviour a little more complex by defining validations specific to our form object. Validations that belong on presenters rather than data models include:

  • Matching password confirmation
  • Acceptance of terms and conditions

In your FormObject subclass, you can override methods to customize the default behaviour. The default behaviour includes:

  • models are built using the new method
  • models are saved using the save method
  • model attributes are set using accessor methods
  • models are validated using the valid? method

You can customise its behaviour by overriding methods. You can add new behaviour by using callbacks (:validation, :save and :persist).

Examples:

Present multiple models and override some default behaviour

class SignupForm < Conformista::FormObject
  presents account: %i[name],
              user: %i[email password],
           profile: %i[twitter github bio]

  private

  def build_profile
    user.build_profile
  end

  def persist_user
    user.save!
  end
end

Instance Method Summary collapse

Methods included from Presenting

present_model, present_models, presents

Constructor Details

#initialize(params = {}) ⇒ FormObject

Returns a new instance of FormObject


60
61
62
# File 'lib/conformista/form_object.rb', line 60

def initialize(params = {})
  set_attributes(params)
end

Instance Method Details

#persisted?Boolean

Whether all presented models are persisted.

Returns:

  • (Boolean)

65
66
67
68
69
# File 'lib/conformista/form_object.rb', line 65

def persisted?
  presented_models.all? do |model|
    send(model.model_name.singular).persisted?
  end
end

#saveObject

Persist all models, if they are all valid. This invokes the :save hook.


73
74
75
76
77
# File 'lib/conformista/form_object.rb', line 73

def save
  run_callbacks :save do
    persist_models
  end
end

#update_attributes(params) ⇒ Object

Delegate the hash of attributes to the presented models and save the object.

Parameters:

  • params (Hash)

See Also:


84
85
86
87
# File 'lib/conformista/form_object.rb', line 84

def update_attributes(params)
  set_attributes(params)
  save
end