Module: NuecaRailsInterfaces::V3::FormInterface::InstanceMethods

Defined in:
lib/nueca_rails_interfaces/v3/form_interface.rb

Overview

Prepended so these methods precede ActiveModel::Model’s versions in the method resolution order. When ‘base.include(ActiveModel::Model)` is called inside the `included` hook, ActiveModel ends up earlier in the ancestor chain, which would otherwise cause ActiveModel::API#initialize to intercept `new` before our param-splitting logic runs.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



69
70
71
72
73
# File 'lib/nueca_rails_interfaces/v3/form_interface.rb', line 69

def method_missing(name, *args, &)
  return @model_instances[name] if @model_instances.key?(name)

  super
end

Instance Method Details

#initialize(options = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/nueca_rails_interfaces/v3/form_interface.rb', line 39

def initialize(options = {})
  @model_instances = {}
  @regular_attributes = extract_regular_attributes(options)

  # Pre-instantiate declared models that were not present in the params
  # (e.g. the form is used in a `new` action with no input yet).
  (self.class.declared_models - @model_instances.keys).each do |model_sym|
    @model_instances[model_sym] = model_sym.to_s.camelize.constantize.new
  end

  super(**@regular_attributes)
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/nueca_rails_interfaces/v3/form_interface.rb', line 75

def respond_to_missing?(name, include_private = false)
  @model_instances.key?(name) || super
end

#valid?(context = nil) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/nueca_rails_interfaces/v3/form_interface.rb', line 52

def valid?(context = nil)
  # Clears errors and runs form-level validations.
  super

  error_key = self.class.flatten_errors? ? :base : nil

  @model_instances.each do |model_name, model_instance|
    next if model_instance.valid?

    model_instance.errors.each do |error|
      errors.add(error_key || model_name, error.full_message)
    end
  end

  errors.empty?
end