title: Refactor: Generating a unique slug for a Model
body: <p>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.</p>
  
  <p>How would you refactor this so that it is still readable, but less verbose and perhaps more clear?</p>
  
  <p><strong>Relationships</strong></p>
  
  <p><em>User</em> has_many :lists</p>
  
  <p><em>List</em> belongs_to :owner</p>
  
  <p><strong>Code</strong></p>
  
  <pre><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 &gt; 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
  </code></pre>