Skip to content

Commit

Permalink
Minor rewrite of slug generation duplicate check.
Browse files Browse the repository at this point in the history
1. Uses "pluck" to pull only the slug column rather than instantiating
all objects.
2. Assumes that the slug ends with a serial number, finds the highest
such serial number, and adds 1 to it
3. This change should make acts_as_url usable for large datasets.
  • Loading branch information
mdchaney committed Aug 6, 2014
1 parent e29d983 commit 09c9468
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions lib/stringex/acts_as_url/adapter/base.rb
Expand Up @@ -18,7 +18,7 @@ def create_callbacks!(klass)
end

def ensure_unique_url!(instance)
@url_owners = nil
@test_urls = nil
self.instance = instance

handle_url!
Expand Down Expand Up @@ -119,10 +119,12 @@ def get_base_url_owner_conditions
end

def handle_duplicate_url!
return if url_owners.none?{|owner| url_attribute_for(owner) == base_url}
n = 1
while url_owners.any?{|owner| url_attribute_for(owner) == duplicate_for_base_url(n)}
n = n.succ
return if test_urls.none?{|test_url| test_url == base_url}
max_id = test_urls.collect { |test_url| test_url =~ /(\d+)\Z/ && $1.to_i }.compact.max
if max_id
n = max_id.succ
else
n = 1
end
write_url_attribute duplicate_for_base_url(n)
end
Expand Down Expand Up @@ -188,8 +190,8 @@ def url_owner_conditions
@url_owner_conditions
end

def url_owners
@url_owners ||= url_owners_class.unscoped.where(url_owner_conditions).to_a
def test_urls
@test_urls ||= url_owners_class.unscoped.where(url_owner_conditions).pluck(settings.url_attribute)
end

def url_owners_class
Expand Down

0 comments on commit 09c9468

Please sign in to comment.