about summary refs log tree commit diff
path: root/app/models/form/domain_block_batch.rb
blob: 39012df517313dde940ebfb475819b99c1382ba8 (plain) (blame)
1
2
3
4
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
# frozen_string_literal: true

class Form::DomainBlockBatch
  include ActiveModel::Model
  include Authorization
  include AccountableConcern

  attr_accessor :domain_blocks_attributes, :action, :current_account

  def save
    case action
    when 'save'
      save!
    end
  end

  private

  def domain_blocks
    @domain_blocks ||= domain_blocks_attributes.values.filter_map do |attributes|
      DomainBlock.new(attributes.without('enabled')) if ActiveModel::Type::Boolean.new.cast(attributes['enabled'])
    end
  end

  def save!
    domain_blocks.each do |domain_block|
      authorize(domain_block, :create?)
      next if DomainBlock.rule_for(domain_block.domain).present?

      domain_block.save!
      DomainBlockWorker.perform_async(domain_block.id)
      log_action :create, domain_block
    end
  end
end