gitlab-org--gitlab-foss/app/models/route.rb

82 lines
2.3 KiB
Ruby
Raw Normal View History

class Route < ActiveRecord::Base
belongs_to :source, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
validates :source, presence: true
validates :path,
length: { within: 1..255 },
presence: true,
uniqueness: { case_sensitive: false }
validate :ensure_permanent_paths, if: :path_changed?
after_create :delete_conflicting_redirects
after_update :delete_conflicting_redirects, if: :path_changed?
2017-05-03 17:14:30 +00:00
after_update :create_redirect_for_old_path
after_update :rename_descendants
2017-03-21 16:04:12 +00:00
scope :inside_path, -> (path) { where('routes.path LIKE ?', "#{sanitize_sql_like(path)}/%") }
def rename_descendants
2017-05-05 17:48:01 +00:00
return unless path_changed? || name_changed?
descendant_routes = self.class.inside_path(path_was)
descendant_routes.each do |route|
2017-05-03 22:26:44 +00:00
attributes = {}
2017-05-03 22:26:44 +00:00
if path_changed? && route.path.present?
attributes[:path] = route.path.sub(path_was, path)
end
2017-05-03 22:26:44 +00:00
if name_changed? && name_was.present? && route.name.present?
attributes[:name] = route.name.sub(name_was, name)
end
2017-05-03 22:26:44 +00:00
if attributes.present?
old_path = route.path
# Callbacks must be run manually
route.update_columns(attributes.merge(updated_at: Time.now))
# 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.
route.create_redirect(old_path, permanent: permanent_redirect?) if attributes[:path]
end
end
end
2017-05-01 23:48:05 +00:00
2017-05-03 17:14:30 +00:00
def delete_conflicting_redirects
conflicting_redirects.delete_all
end
def conflicting_redirects
RedirectRoute.temporary.matching_path_and_descendants(path)
2017-05-03 17:14:30 +00:00
end
def create_redirect(path, permanent: false)
RedirectRoute.create(source: source, path: path, permanent: permanent)
2017-05-01 23:48:05 +00:00
end
2017-05-03 17:33:01 +00:00
private
def create_redirect_for_old_path
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, "#{path} has been taken before. Please use another one") if conflicting_redirect_exists?
end
def conflicting_redirect_exists?
RedirectRoute.permanent.matching_path_and_descendants(path).exists?
2017-05-03 17:33:01 +00:00
end
end