I'm currently generating url slugs dynamically for my models (and implementing to_param/self.from_param to interpret them). My slug generation code feels verbose, and could use a refactor.
How would you refactor this so that it is still readable, but less verbose and perhaps more clear?
Relationships
User has_many :lists
List belongs_to :owner
Code
def generate_slug
if self.owner
slug_found = false
count = 0
temp_slug = to_slug
until slug_found
# increment the count
count += 1
# create a potential slug
temp_slug = if count > 1
suffix = "_" + count.to_s
to_slug + suffix
else
to_slug
end
# fetch an existing slug for this list's owner's lists
# (i.e. owner has many lists and list slugs should be unique per owner)
existing = self.owner.lists.from_param(temp_slug)
# if it doesn't exist, or it exists but is the current list, slug found!
if existing.nil? or (existing == self)
slug_found = true
end
end
# set the slug
self.slug = temp_slug
else
Rails.logger.debug "List (id: #{self.id}, slug: #{self.slug}) doesn't have an owner set!"
end
end