Question

Let's say I have two models that both have same callbacks:

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

Where can I put the shared callback code? Thanks

 def normalizeDate
   self.created_at = return_DateTime(self.created_at)
 end
Was it helpful?

Solution

Marek's answer is good but the Rails way is:

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.

(and you have a decicated folder for it: models/concerns)

OTHER TIPS

You can define your own module:

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

and include it in every class you want this behavior:

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

I'm not sure if my code is free of error (I didn't test it), treat it as an example.

The Rails 4 way is to use ActiveSupport::Concern

File 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

File model/entry.rb

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

  belongs_to :patient
  validates :text, presence: true
end

File models/post.rb

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

Note: I renamed for you normalizeDate to normalize_date

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top