Class: FullMetalBody::SaveBlockedKeysService

Inherits:
Object
  • Object
show all
Defined in:
lib/full_metal_body/services/save_blocked_keys_service.rb

Class Method Summary collapse

Class Method Details

.execute!(controller_path, action_name, blocked_keys) ⇒ ActiveRecord::Result

Save blocked_keys to the database using bulk insert.

Parameters:

  • controller_path (String)
  • action_name (String)
  • blocked_keys (Array<Array<String>>)

Returns:

  • (ActiveRecord::Result)


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/full_metal_body/services/save_blocked_keys_service.rb', line 14

def execute!(controller_path, action_name, blocked_keys)
  ApplicationRecord.transaction do
    blocked_action = BlockedAction.find_or_create_by!(controller: controller_path, action: action_name)
    now = Time.zone.now
    if rails_6_1_and_up?
      attributes = blocked_keys.map { |key| { blocked_key: key } }
      blocked_action.blocked_keys.create_with(
        created_at: now,
        updated_at: now,
        ).insert_all(attributes, returning: [:id], unique_by: [:blocked_action_id, :blocked_key])
    elsif rails_6_0?
      attributes = blocked_keys.map do |key|
        {
          blocked_action_id: blocked_action.id,
          blocked_key: key,
          created_at: now,
          updated_at: now,
        }
      end
      blocked_action.blocked_keys.insert_all(
        attributes,
        returning: [:id],
        unique_by: [:blocked_action_id, :blocked_key],
        )
    else
      blocked_keys.each { |key| blocked_action.blocked_keys.find_or_create_by(blocked_key: key) }
    end
  end
end