Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put custom callbacks that I use in several models

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
like image 982
John Smith Avatar asked Dec 12 '22 06:12

John Smith


2 Answers

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)

like image 141
apneadiving Avatar answered Feb 19 '23 07:02

apneadiving


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.

like image 39
Marek Lipka Avatar answered Feb 19 '23 07:02

Marek Lipka