Module: Formotion::Formable

Defined in:
lib/formotion/model/formable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
# File 'lib/formotion/model/formable.rb', line 3

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#on_submitObject

what happens when the form is submitted?



95
96
97
# File 'lib/formotion/model/formable.rb', line 95

def on_submit
  p "need to implement on_submit in your Formable model #{self.class.to_s}"
end

#to_formObject

Creates a Formotion::Form out of the model



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/formotion/model/formable.rb', line 57

def to_form
  rows = self.class.form_properties.collect { |options|
    {
      title: options[:property].capitalize,
      key: options[:property],
      type: options[:row_type],
      value: self.send(options[:property])
    }.merge(options)
  }
  form_hash = {
    title: self.class.form_title || self.class.to_s.capitalize,
    sections: [{
      rows: rows
    }]
  }

  form = Formotion::Form.new(form_hash)
  form.on_submit do
    self.on_submit
  end

  # Use the :transform lambdas passed in form_property
  form.sections.first.rows.each_with_index { |row, index|
    row.instance_variable_set("@formable_options", self.class.form_properties[index])
    if self.class.form_properties[index][:transform]
      row.class.send(:alias_method, :old_value_setter, :value=)
      row.instance_eval do
        def value=(value)
          old_value_setter(@formable_options[:transform].call(value))
        end
      end
    end
  }

  form
end