0

I have 2 models using 2 similar methods. Both of them called are generate and both are called by before_save. I want to refactor them into one. How can I do that?

#model1's generate
before_save :generate
def generate
  self.slug = self.title.gsub(' ', '-').downcase
end

#model2‘s generate
before_save :generate
def generate
  self.slug = self.name.gsub(' ', '-').downcase
end
4

1 回答 1

1

使用ActiveSupport::Concern

module Slugged
  extend ActiveSupport::Concern

  included do
    before_save :generate
  end

  def slugged_attr
    name
  end

  def generate
    self.slug = self.slugged_attr.gsub(' ', '-').downcase
  end
end

然后将其包含到您的模型中。

include Slugged

将以下方法添加到您的第一个模型。它将覆盖 slugged_attr 关注:

def slugged_attr
  title
end
于 2013-09-01T12:28:08.820 回答