重构:为模型生成一个独特的slug

时间:2012-10-11 01:27:42

标签: ruby-on-rails ruby optimization refactoring

我正在为我的模型动态生成url slugs(并实现to_param / self.from_param来解释它们)。我的slug代码感觉很冗长,可以使用重构器。

你会如何重构它以使它仍然可读,但不那么冗长,也许更清晰?

关系

用户 has_many:列表

列表 belongs_to:所有者

代码

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

1 个答案:

答案 0 :(得分:1)

你可以这样做

def generate_slug
  return Rails.logger.debug "List (id: #{self.id}, slug: #{self.slug}) doesn't have an owner set!" if !self.owner

  count = 1
  begin
    temp_slug = %Q!#{to_slug}#{"_#{count}" if count > 1}!
    existing = self.owner.lists.from_param(temp_slug)

    if existing.nil? or (existing == self)
      self.slug = temp_slug
    end
  end while count += 1
end

但有两件事。首先你有一个无限循环,这是不好的。其次,不是循环检查每次是否存在对象以及您需要增加后缀,最好先获取最后一个现有列表,然后再添加一个。