Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Allows mass assignment of custom date formats to date columns in ActiveRecord columns
before_validation :ensure_default_date_format
# Parses dates in european date formats before saving a record
# Accepts dates in the format "" and "yyyy-mm-dd"
def ensure_default_date_format {|c| c.type == :date}.each do |c|
value_before_type_cast = send("#{}_before_type_cast")
date = Date.try(:parse, value_before_type_cast, :eu) || Date.parse(value_before_type_cast)
write_attribute(, date)
# Date class extension to parse custom formats by passing in the format symbol
# This came from a StackOverflow question afair, I'll add it as soon as I find it.
class Date
class << self
alias orig_parse parse
def self.parse(_string, _format = nil)
return Date.orig_parse(_string) unless _format
Date.strptime(_string, Date::DATE_FORMATS[_format])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment