在哪里放置我在几个模型中使用的自定义回调

时间:2014-05-09 08:16:04

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 callback

假设我有两个模型都有相同的回调:

class Entry < ActiveRecord::Base
    belongs_to :patient
    validates :text, presence: true
    after_validation :normalizeDate

    def normalizeDate
      self.created_at = return_DateTime(self.created_at)
    end
end

class Post < ActiveRecord::Base
    after_validation :normalizeDate

    def normalizeDate
      self.created_at = return_DateTime(self.created_at)
    end
end

我可以在哪里放置共享回调代码?感谢

 def normalizeDate
   self.created_at = return_DateTime(self.created_at)
 end

3 个答案:

答案 0 :(得分:8)

马雷克的答案很好,但Rails方式是:

module NormalizeDateModule
  extend ActiveSupport::Concern

  included do
    after_validation :normalize_date
  end

  def normalize_date
    self.created_at = return_DateTime(created_at)
  end
end

Doc here

(你有一个假定的文件夹:模型/关注点)

答案 1 :(得分:3)

您可以定义自己的模块:

module NormalizeDateModule
  def self.included(base)
    base.class_eval do
      after_validation :normalize_date
    end
  end

  def normalize_date
    self.created_at = return_DateTime(created_at)
  end
end

并将其包含在您希望此行为的每个类中:

class Entry < ActiveRecord::Base
  include NormalizeDateModule
  # ...
end

我不确定我的代码是否没有错误(我没有测试它),把它作为一个例子。

答案 2 :(得分:2)

Rails 4方式是使用ActiveSupport::Concern

档案 models / concerns / date_normalizer.rb

module Concerns
  module DateNormalizer
    extend ActiveSupport::Concern

    included do |base|
      base.after_validation :normalize_date
    end

    def normalize_date
      self.created_at = return_DateTime(self.created_at)
    end
  end
end

文件 model / entry.rb

class Entry < ActiveRecord::Base
  include Concerns::DateNormalizer

  belongs_to :patient
  validates :text, presence: true
end

档案 models / post.rb

class Post < ActiveRecord::Base
  include Concerns::DateNormalizer
end

注意:我已将normalizeDate重命名为normalize_date