Created
June 22, 2014 21:51
-
-
Save kivanio/6bee070bc9c835515b0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support/concern' | |
module ActiveModel | |
module DatetimeAttributes | |
extend ActiveSupport::Concern | |
included do | |
def self.attr_datetime(datetime_attribute, options = {}) | |
time_attr = options[:time_attr] || :"#{datetime_attribute}_time" | |
date_attr = options[:date_attr] || :"#{datetime_attribute}_date" | |
attr_writer date_attr | |
attr_writer time_attr | |
after_initialize do | |
date = instance_variable_get("@#{date_attr}") | |
time = instance_variable_get("@#{time_attr}") | |
if date && time | |
send("#{datetime_attribute}=", Time.zone.parse("#{date} #{time}")) | |
end | |
end | |
define_method "#{date_attr}" do | |
send("#{datetime_attribute}").try(:strftime, "%Y-%m-%d") | |
end | |
define_method "#{time_attr}" do | |
send("#{datetime_attribute}").try(:strftime, "%H:%M") | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment