about summary refs log tree commit diff
path: root/app/models/status_domain_permission.rb
blob: f9e5dc55ec47a251eb0f82ab89497f0bb6716d37 (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true
# == Schema Information
#
# Table name: status_domain_permissions
#
#  id         :bigint(8)        not null, primary key
#  status_id  :bigint(8)        not null
#  domain     :string           default(""), not null
#  visibility :integer          default("public"), not null
#

class StatusDomainPermission < ApplicationRecord
  include Paginable

  belongs_to :status, inverse_of: :domain_permissions
  enum visibility: [:public, :unlisted, :private, :direct, :limited], _suffix: :visibility

  class << self
    def create_by_domains(permissions_list)
      Array(permissions_list).map(&method(:normalize)).map do |permissions|
        where(**permissions).first_or_create
      end
    end

    def create_by_domains!(permissions_list)
      Array(permissions_list).map(&method(:normalize)).map do |permissions|
        where(**permissions).first_or_create!
      end
    end

    def create_or_update(domain_permissions)
      domain_permissions = normalize(domain_permissions)
      permissions = find_by(domain: domain_permissions[:domain])
      if permissions.present?
        permissions.update(**domain_permissions)
      else
        create(**domain_permissions)
      end
      permissions
    end

    def create_or_update!(domain_permissions)
      domain_permissions = normalize(domain_permissions)
      permissions = find_by(domain: domain_permissions[:domain])
      if permissions.present?
        permissions.update!(**domain_permissions)
      else
        create!(**domain_permissions)
      end
      permissions
    end

    private

    def normalize(hash)
      hash.symbolize_keys!
      hash[:domain] = hash[:domain].strip.downcase
      hash.compact
    end
  end
end