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

56 lines
1.5 KiB
Ruby
Raw Normal View History

class Route < ActiveRecord::Base
belongs_to :source, polymorphic: true
validates :source, presence: true
validates :path,
length: { within: 1..255 },
presence: true,
uniqueness: { case_sensitive: false }
2017-05-03 17:14:30 +00:00
after_save :delete_conflicting_redirects
after_update :create_redirect_for_old_path
2017-05-01 23:48:05 +00:00
after_update :rename_direct_descendant_routes
2017-03-21 16:04:12 +00:00
scope :inside_path, -> (path) { where('routes.path LIKE ?', "#{sanitize_sql_like(path)}/%") }
2017-05-01 23:48:05 +00:00
scope :direct_descendant_routes, -> (path) { where('routes.path LIKE ? AND routes.path NOT LIKE ?', "#{sanitize_sql_like(path)}/%", "#{sanitize_sql_like(path)}/%/%") }
2017-03-21 16:04:12 +00:00
2017-05-01 23:48:05 +00:00
def rename_direct_descendant_routes
2017-05-03 22:26:44 +00:00
return if !path_changed? && !name_changed?
2017-05-03 22:26:44 +00:00
direct_descendant_routes = self.class.direct_descendant_routes(path_was)
2017-05-03 22:26:44 +00:00
direct_descendant_routes.each do |route|
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
route.update(attributes) unless attributes.empty?
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.matching_path_and_descendants(path)
end
def create_redirect(path)
RedirectRoute.create(source: source, path: path)
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) if path_changed?
end
end