Skip to content

Instantly share code, notes, and snippets.

@bloudermilk
Created February 7, 2013 02:34
Show Gist options
  • Select an option

  • Save bloudermilk/4727949 to your computer and use it in GitHub Desktop.

Select an option

Save bloudermilk/4727949 to your computer and use it in GitHub Desktop.
Puts Chronic in front of date, time, and datetime attributes to allow for flexile input (anything supported by Chronic)
module ChronicAttribute
extend ActiveSupport::Concern
module ClassMethods
def chronic(*attrs)
attrs.each do |attr|
define_method "#{attr}=" do |value|
if value.is_a? String
with_utc do
self[attr] = Chronic.parse(value)
end
else
super(value)
end
end
end
end
end
private
def with_utc
old_class = Chronic.time_class
Time.use_zone("UTC") do
Chronic.time_class = Time.zone
yield
end
ensure
Chronic.time_class = old_class
end
end
class Task < ActiveRecord::Base
include ChronicAttribute
chronic :due_date
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment