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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With