Class: Reform::Form::Validate::Populator::PopulateIfEmpty

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

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ PopulateIfEmpty

Returns a new instance of PopulateIfEmpty.



23
24
25
26
27
# File 'lib/reform/form/validate.rb', line 23

def initialize(*args)
  @fields, @fragment, args = args
  @index = args.first
  @args  = args.last
end

Instance Method Details

#callObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/reform/form/validate.rb', line 29

def call
  binding = @args.binding
  form    = binding.get

  parent_form =  @args.user_options[:parent_form]
  form_model    = parent_form.model # FIXME: sort out who's responsible for sync.

  return if binding.array? and form and form[@index] # TODO: this should be handled by the Binding.
  return if !binding.array? and form
  # only get here when above form is nil.

  if binding[:populate_if_empty].is_a?(Proc)
    model = parent_form.instance_exec(@fragment, @args, &binding[:populate_if_empty]) # call user block.
  else
    model = binding[:populate_if_empty].new
  end

  form  = binding[:form].new(model) # free service: wrap model with Form. this usually happens in #setup.

  if binding.array?
    form_model.send("#{binding.getter}") << model # FIXME: i don't like this, but we have to add the model to the parent object to make associating work. i have to use #<< to stay compatible with AR's has_many API. DISCUSS: what happens when we get out-of-sync here?
    @fields.send("#{binding.getter}")[@index] = form
  else
    form_model.send("#{binding.setter}", model) # FIXME: i don't like this, but we have to add the model to the parent object to make associating work.
    @fields.send("#{binding.setter}", form) # :setter is currently overwritten by :parse_strategy.
  end
end