gitlab-org--gitlab-foss/app/models/application_record.rb
Sean McGivern 79dd92c818 Optimise upload path calls
String#underscore isn't particularly slow, but it's possible for us to
call it many times in a users autocomplete request, with mostly-static
values ('User', 'Group', etc.). We can memoise this and save a
surprising amount of time (around 10% of the total request time in some
cases).
2019-05-14 11:01:48 -05:00

48 lines
933 B
Ruby

# frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
alias_method :reset, :reload
def self.id_in(ids)
where(id: ids)
end
def self.id_not_in(ids)
where.not(id: ids)
end
def self.pluck_primary_key
where(nil).pluck(self.primary_key)
end
def self.safe_ensure_unique(retries: 0)
transaction(requires_new: true) do
yield
end
rescue ActiveRecord::RecordNotUnique
if retries > 0
retries -= 1
retry
end
false
end
def self.safe_find_or_create_by!(*args)
safe_find_or_create_by(*args).tap do |record|
record.validate! unless record.persisted?
end
end
def self.safe_find_or_create_by(*args)
safe_ensure_unique(retries: 1) do
find_or_create_by(*args)
end
end
def self.underscore
Gitlab::SafeRequestStore.fetch("model:#{self}:underscore") { self.to_s.underscore }
end
end