Class: BetterParams::ParamsDestroyInfo

Inherits:
Object
  • Object
show all
Defined in:
lib/better_params/params_destroy_info.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add(*args) ⇒ Object



3
4
5
# File 'lib/better_params/params_destroy_info.rb', line 3

def self.add(*args)
  new.add(*args)
end

Instance Method Details

#add(original_params, object, *keys) ⇒ Object

For all has_many relations from a keys array adds information about destroying objects by an algorythm: If a nested object doesn’t exists in a passed object it will be destroyed.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/better_params/params_destroy_info.rb', line 10

def add(original_params, object, *keys)
  return original_params if object.nil?

  # Process every key and merge updated information to params
  prepare_keys(keys).reduce(original_params) do |params, (key, nested_keys)|
    # Don't needs to process key if params is not passed
    nested_params = params[key]
    next params if nested_params.nil?

    # Try to fetch relation value
    relation = object.public_send(relation_key(key))

    # Can't process key if a nested object doesn't exists
    next params if relation.nil?

    if relation.is_a? Enumerable
      # If a relation is a has_many, needs to add information about destroying
      nested_params = add_destroy_info(nested_params, relation)

      # Needs to go deeper to the every object in an array if has nested keys
      unless nested_keys.nil?
        nested_params = add_nested_destroy_info(
          nested_params, relation, nested_keys
        )
      end
    else
      # If a relation is a single object we needs to go deeper
      nested_params = add(nested_params, relation, *nested_keys)
    end

    next params.merge(key => nested_params)
  end
end