about summary refs log tree commit diff
path: root/app/models/status_domain_permission.rb
blob: be767a2b63e90444ece610b782c9dec395a7c8fa (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
62
63
64
65
66
67
68
69
# 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
  include Cacheable

  validates :domain, presence: true, uniqueness: { scope: :status_id }
  validates :visibility, presence: true

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

  default_scope { order(domain: :desc) }

  cache_associated :status

  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