Skip to content

Instantly share code, notes, and snippets.

@coreyward
Created July 21, 2017 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreyward/6a26421d3e994b2b7b12dfffa951b909 to your computer and use it in GitHub Desktop.
Save coreyward/6a26421d3e994b2b7b12dfffa951b909 to your computer and use it in GitHub Desktop.
Copy-pasteable Rails initializer that will handle date to string conversion and parsing (with output as MM/DD/YYYY by default)
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
module FixDateFormatting
class EasyDate < ActiveRecord::Type::Date
def cast_value(value)
default = super
parsed = Chronic.parse(value)&.to_date if value.is_a?(String)
parsed || default
end
end
def inherited(subclass)
super
date_attributes = subclass.attribute_types.select { |_, type| ActiveRecord::Type::Date === type }
date_attributes.each do |name, _type|
subclass.attribute name, EasyDate.new
end
end
end
Rails.application.config.to_prepare do
ApplicationRecord.extend(FixDateFormatting)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment