Module: Formality::ClassMethods

Defined in:
lib/formality.rb,
lib/formality.rb,
lib/formality.rb,
lib/formality.rb

Overview

Nesting

Allows forms to have forms nested within them that work nicely with Rails’ :fields_for method.

Validations are called on nested forms, so that if any nested form is invalid, so is the parent.

Instance Method Summary collapse

Instance Method Details

#assign(attrs) ⇒ Object

A convenience class method for creating and assigning a Hash to a form.



77
78
79
# File 'lib/formality.rb', line 77

def assign(attrs)
  new.assign(attrs)
end

#attribute(name, options = {}) ⇒ Object

Declare an attribute.

Defines a reader and writer. Accepts a :default options for the default value of the attribute.



64
65
66
67
68
# File 'lib/formality.rb', line 64

def attribute(name, options={})
  attributes << name.to_s
  define_reader(name, options[:default])
  attr_writer name
end

#attributesObject

A Set of attribute names, stored on the form class.



71
72
73
# File 'lib/formality.rb', line 71

def attributes
  @__attributes ||= Set.new
end

#from_model(model) ⇒ Object

Build a form object from an existing model.

If nested forms were declared with the :from_model_attribute option, it will also build the nested form object(s).



147
148
149
150
151
152
153
154
155
# File 'lib/formality.rb', line 147

def from_model(model)
  new.tap do |form|
    form.id = model.id
    form.assign(model.attributes)
    nested_forms.each do |nested|
      form.send("#{nested}=", model)
    end
  end
end

#model(name_sym) ⇒ Object

Declare the model that this form object represents.

Purely a convenience so that you don’t have to specify the :url parameter in your :form_for calls.



137
138
139
140
# File 'lib/formality.rb', line 137

def model(name_sym)
  model_klass = name_sym.to_s.capitalize.constantize
  @__model_name = ActiveModel::Name.new(model_klass)
end

#model_nameObject

:model_name must be defined on the class and return a String with various convenience methods. ActiveModel::Name gives us that.

By default, :model_name uses the name of the Form class.



27
28
29
# File 'lib/formality.rb', line 27

def model_name
  @__model_name ||= ActiveModel::Name.new(self)
end

#nest_many(children, options = {}) ⇒ Object

Plural nesting.

Works just like :nest_one, except it works for an Array of nested forms.



207
208
209
210
# File 'lib/formality.rb', line 207

def nest_many(children, options={})
  add_nested_form(children)
  define_nested_form_many(children, options)
end

#nest_one(child, options = {}) ⇒ Object

Singular Nesting.



198
199
200
201
# File 'lib/formality.rb', line 198

def nest_one(child, options={})
  add_nested_form(child)
  define_nested_form_one(child, options)
end

#nested_formsObject

Keep track of what forms we’ve nested.



213
214
215
# File 'lib/formality.rb', line 213

def nested_forms
  @__nested_forms ||= Set.new
end