File: route.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (56 lines) | stat: -rw-r--r-- 1,878 bytes parent folder | download
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
# frozen_string_literal: true

class Route < ApplicationRecord
  include CaseSensitivity
  include Gitlab::SQL::Pattern
  include EachBatch

  belongs_to :source, polymorphic: true, inverse_of: :route # rubocop:disable Cop/PolymorphicAssociations
  belongs_to :namespace, inverse_of: :namespace_route
  validates :source, presence: true

  validates :path,
    length: { within: 1..255 },
    presence: true,
    uniqueness: { case_sensitive: false }

  after_create :delete_conflicting_redirects
  after_update :delete_conflicting_redirects, if: :saved_change_to_path?
  after_update :create_redirect_for_old_path
  after_update :rename_descendants

  scope :by_paths, ->(paths) { where(arel_table[:path].lower.in(paths.map(&:downcase))) }
  scope :inside_path, ->(path) { where('routes.path LIKE ?', "#{sanitize_sql_like(path)}/%") }
  scope :for_routable, ->(routable) { where(source: routable) }
  scope :for_routable_type, ->(routable_type) { where(source_type: routable_type) }
  scope :sort_by_path_length, -> { order('LENGTH(routes.path)', :path) }

  def rename_descendants
    return unless saved_change_to_path? || saved_change_to_name?

    changes = {
      path: { saved: saved_change_to_path?, old_value: path_before_last_save },
      name: { saved: saved_change_to_name?, old_value: name_before_last_save }
    }

    Routes::RenameDescendantsService.new(self).execute(changes) # rubocop: disable CodeReuse/ServiceClass -- Need a service class to encapsulate all the logic.
  end

  def delete_conflicting_redirects
    conflicting_redirects.delete_all
  end

  def conflicting_redirects
    RedirectRoute.matching_path_and_descendants(path)
  end

  def create_redirect(path)
    RedirectRoute.create(source: source, path: path)
  end

  private

  def create_redirect_for_old_path
    create_redirect(path_before_last_save) if saved_change_to_path?
  end
end