Skip to content

Instantly share code, notes, and snippets.

@chimame
Last active August 29, 2015 14:27
Show Gist options
  • Save chimame/97db457083e930941323 to your computer and use it in GitHub Desktop.
Save chimame/97db457083e930941323 to your computer and use it in GitHub Desktop.
datetime integratable for ActiveRecord
module DatetimeIntegratable
extend ActiveSupport::Concern
included do
after_initialize :initialize_integrate_datetime
def initialize_integrate_datetime
self.class.datetime_integrate_targets.each do |attribute|
decompose_datetime(attribute)
end
end
def integrate_datetime(attribute)
date = self.send("#{attribute}_date")
hour = self.send("#{attribute}_hour")
minute = self.send("#{attribute}_minute")
second = self.send("#{attribute}_second")
if date.present? && hour.present? && minute.present?
self.send("#{attribute}=", "#{date} #{hour}:#{minute}:#{second.present? ? second : '00'}")
else
self.send("#{attribute}=", nil)
end
rescue
nil
end
def decompose_datetime(attribute)
return unless self.respond_to?("#{attribute}")
original_date = self.send("#{attribute}")
return if original_date.nil?
[["date", "%Y/%m/%d"], ["hour", "%H"], ["minute", "%M"], ["second", "%S"]].each do |key, format|
return if self.send("#{attribute}_#{key}").present?
self.send("#{attribute}_#{key}=", original_date.strftime(format))
end
end
end
module ClassMethods
attr_accessor :datetime_integrate_targets
def integrate_datetime_fields(*attributes)
self.datetime_integrate_targets = attributes
attributes.each do |attribute|
self.send(:attr_accessor, "#{attribute}_date")
self.send(:attr_accessor, "#{attribute}_hour")
self.send(:attr_accessor, "#{attribute}_minute")
self.send(:attr_accessor, "#{attribute}_second")
define_method("#{attribute}_date=") do |value|
self.instance_variable_set("@#{attribute}_date", value)
integrate_datetime(attribute)
value
end
define_method("#{attribute}_hour=") do |value|
self.instance_variable_set("@#{attribute}_hour", value)
integrate_datetime(attribute)
value
end
define_method("#{attribute}_minute=") do |value|
self.instance_variable_set("@#{attribute}_minute", value)
integrate_datetime(attribute)
value
end
define_method("#{attribute}_second=") do |value|
self.instance_variable_set("@#{attribute}_second", value)
integrate_datetime(attribute)
value
end
define_method("#{attribute}=") do |value|
super value
decompose_datetime(attribute)
value
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment