Class: Aform::Form

Inherits:
Object
  • Object
show all
Defined in:
lib/aform/form.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, attributes, parent = nil, opts = {}) ⇒ Form

Returns a new instance of Form.



7
8
9
10
11
12
13
14
# File 'lib/aform/form.rb', line 7

def initialize(model, attributes, parent = nil, opts = {})
  @opts = opts
  @attributes = attributes
  @model = model
  @parent = parent
  assign_opts_instances
  initialize_nested
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



5
6
7
# File 'lib/aform/form.rb', line 5

def attributes
  @attributes
end

#form_modelObject (readonly)

Returns the value of attribute form_model.



5
6
7
# File 'lib/aform/form.rb', line 5

def form_model
  @form_model
end

#modelObject (readonly)

Returns the value of attribute model.



5
6
7
# File 'lib/aform/form.rb', line 5

def model
  @model
end

#nested_formsObject (readonly)

Returns the value of attribute nested_forms.



5
6
7
# File 'lib/aform/form.rb', line 5

def nested_forms
  @nested_forms
end

#parentObject (readonly)

Returns the value of attribute parent.



5
6
7
# File 'lib/aform/form.rb', line 5

def parent
  @parent
end

Class Method Details

.method_missing(meth, *args, &block) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/aform/form.rb', line 54

def method_missing(meth, *args, &block)
  if meth.to_s.start_with?("validate")
    options = {method: meth, options: args}
    options.merge!(block: block) if block_given?
    self.validations ||= []
    self.validations << options
  elsif meth == :has_many
    define_nested_form(args, &block)
  else
    super
  end
end

.param(*args) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/aform/form.rb', line 44

def param(*args)
  self.params ||= []
  options = args.extract_options!
  elements = args.map do |a|
    field = {field: a}
    options.present? ? field.merge({options: options}) : field
  end
  self.params += elements
end

.primary_key(key) ⇒ Object



40
41
42
# File 'lib/aform/form.rb', line 40

def primary_key(key)
  self.pkey = key
end

Instance Method Details

#errorsObject



35
36
37
# File 'lib/aform/form.rb', line 35

def errors
  @errors.messages
end

#invalid?Boolean

Returns:

  • (Boolean)


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

def invalid?
  !valid?
end

#saveObject



31
32
33
# File 'lib/aform/form.rb', line 31

def save
  self.valid? && @form_saver.save
end

#valid?Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
# File 'lib/aform/form.rb', line 16

def valid?
  if @nested_forms
    main = @form_model.valid?
    #all? don't invoike method on each element
    nested = @nested_forms.values.flatten.map(&:valid?).all?
    main && nested
  else
    @form_model.valid?
  end
end