Class: Conformista::FormObject
- Inherits:
-
Object
- Object
- Conformista::FormObject
- 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
newmethod - models are saved using the
savemethod - 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).
Instance Method Summary collapse
-
#initialize(params = {}) ⇒ FormObject
constructor
A new instance of FormObject.
-
#persisted? ⇒ Boolean
Whether all presented models are persisted.
-
#save ⇒ Object
Persist all models, if they are all valid.
-
#update_attributes(params) ⇒ Object
Delegate the hash of attributes to the presented models and save the object.
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.
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 |
#save ⇒ Object
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.
84 85 86 87 |
# File 'lib/conformista/form_object.rb', line 84 def update_attributes(params) set_attributes(params) save end |