如何在rails中组织共享模型助手

时间:2015-07-02 15:35:56

标签: ruby-on-rails friendly-id

我有两个类似的slug生成方法的模型。如下图所示:

def generate_reference
    self_id = self.id.present? ? (sprintf '%04d', self.id) : '0000'
    [
        REFERENCE_CODE[:request], 
        Time.now.strftime('%Y%M'),
        Time.now.strftime('%S%2N')].join('-')
end

def remake_slug
    self.update_attribute(:reference, nil)
    self.save!
end

唯一会改变的是REFERENCE_CODE[:request]。它在不同的模型中有所不同。例如:

request.rb

extend FriendlyId
friendly_id :generate_reference, use: :slugged, slug_column: 'reference'
after_create :remake_slug

def generate_reference
   [REFERENCE_CODE[:request]...]
end

def remake_slug
    self.update_attribute(:reference, nil)
    self.save!
end

并在 booking.rb

extend FriendlyId
friendly_id :generate_reference, use: :slugged, slug_column: 'reference'
after_create :remake_slug

def generate_reference
   [REFERENCE_CODE[:booking]...]
end

def remake_slug
    self.update_attribute(:reference, nil)
    self.save!
end

有大量重复的代码。我想知道我应该如何组织slug创建逻辑以使其更清洁?

0 个答案:

没有答案