Where to put custom callbacks that I use in several models

Let's say I have two models that have the 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 a common callback code? Thanks

 def normalizeDate
   self.created_at = return_DateTime(self.created_at)
 end
+4
source share
3 answers

Marek's answer is good, but the Rails path:

module NormalizeDateModule
  extend ActiveSupport::Concern

  included do
    after_validation :normalize_date
  end

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

The dock is here .

(and you have a folder with replicas: models / problems)

+8
source

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 need:

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

I'm not sure that my code is error free (I have not tested it), consider it as an example.

+3
source

Rails 4 ActiveSupport::Concern

//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 normalizeDatetonormalize_date

+2
source

Source: https://habr.com/ru/post/1539883/


All Articles