Module: BetterParams::Base::ConvertKeys

Included in:
BetterParams::Base
Defined in:
lib/better_params/base/convert_keys.rb

Instance Method Summary collapse

Instance Method Details

#convert_keys(keys, &block) ⇒ Object

Not used directly



5
6
7
8
9
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
# File 'lib/better_params/base/convert_keys.rb', line 5

def convert_keys(keys, &block)
  merge_attributes = ->(params, key, attributes) do
    params.merge(block.call(key) => attributes).except(key)
  end

  params = self
  keys.each do |key|
    if key.is_a? Hash
      key.each do |nested_key, key_from_key|
        nested_params = params[nested_key]
        next if nested_params.nil?

        nested_attributes =
          if nested_params.is_a?(Array)
            nested_params.map do |item|
              item.convert_keys(key_from_key, &block)
            end
          else
            nested_params.convert_keys(key_from_key, &block)
          end

        params = merge_attributes.call(
          params,
          nested_key,
          nested_attributes
        )
      end
    else
      attributes = params[key]
      next if attributes.nil?

      params = merge_attributes.call(params, key, attributes)
    end
  end

  params
end