debian-mirror-gitlab/app/models/route.rb

94 lines
2.6 KiB
Ruby
Raw Normal View History

2017-08-17 22:00:37 +05:30
class Route < ActiveRecord::Base
2018-03-17 18:26:18 +05:30
include CaseSensitivity
2017-09-10 17:25:29 +05:30
belongs_to :source, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
2017-08-17 22:00:37 +05:30
validates :source, presence: true
validates :path,
length: { within: 1..255 },
presence: true,
uniqueness: { case_sensitive: false }
2018-03-17 18:26:18 +05:30
validate :ensure_permanent_paths, if: :path_changed?
before_validation :delete_conflicting_orphaned_routes
2017-08-17 22:00:37 +05:30
after_create :delete_conflicting_redirects
after_update :delete_conflicting_redirects, if: :path_changed?
after_update :create_redirect_for_old_path
after_update :rename_descendants
scope :inside_path, -> (path) { where('routes.path LIKE ?', "#{sanitize_sql_like(path)}/%") }
def rename_descendants
return unless path_changed? || name_changed?
descendant_routes = self.class.inside_path(path_was)
descendant_routes.each do |route|
attributes = {}
if path_changed? && route.path.present?
attributes[:path] = route.path.sub(path_was, path)
end
if name_changed? && name_was.present? && route.name.present?
attributes[:name] = route.name.sub(name_was, name)
end
if attributes.present?
old_path = route.path
# Callbacks must be run manually
2017-09-10 17:25:29 +05:30
route.update_columns(attributes.merge(updated_at: Time.now))
2017-08-17 22:00:37 +05:30
# We are not calling route.delete_conflicting_redirects here, in hopes
# of avoiding deadlocks. The parent (self, in this method) already
# called it, which deletes conflicts for all descendants.
2018-03-17 18:26:18 +05:30
route.create_redirect(old_path, permanent: permanent_redirect?) if attributes[:path]
2017-08-17 22:00:37 +05:30
end
end
end
def delete_conflicting_redirects
conflicting_redirects.delete_all
end
def conflicting_redirects
2018-03-17 18:26:18 +05:30
RedirectRoute.temporary.matching_path_and_descendants(path)
2017-08-17 22:00:37 +05:30
end
2018-03-17 18:26:18 +05:30
def create_redirect(path, permanent: false)
RedirectRoute.create(source: source, path: path, permanent: permanent)
2017-08-17 22:00:37 +05:30
end
private
def create_redirect_for_old_path
2018-03-17 18:26:18 +05:30
create_redirect(path_was, permanent: permanent_redirect?) if path_changed?
end
def permanent_redirect?
source_type != "Project"
end
def ensure_permanent_paths
return if path.nil?
errors.add(:path, "has been taken before") if conflicting_redirect_exists?
end
def conflicting_redirect_exists?
RedirectRoute.permanent.matching_path_and_descendants(path).exists?
end
def delete_conflicting_orphaned_routes
conflicting = self.class.iwhere(path: path)
conflicting_orphaned_routes = conflicting.select do |route|
route.source.nil?
end
conflicting_orphaned_routes.each(&:destroy)
2017-08-17 22:00:37 +05:30
end
end