Skip to content

Instantly share code, notes, and snippets.

@stex
Last active December 17, 2015 15:09
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 stex/5629957 to your computer and use it in GitHub Desktop.
Save stex/5629957 to your computer and use it in GitHub Desktop.
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 "dd.mm.yyyy" and "yyyy-mm-dd"
#--------------------------------------------------------------
def ensure_default_date_format
self.class.columns.select {|c| c.type == :date}.each do |c|
value_before_type_cast = send("#{c.name}_before_type_cast")
date = Date.try(:parse, value_before_type_cast, :eu) || Date.parse(value_before_type_cast)
write_attribute(c.name, date)
end
end
# 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
end
def self.parse(_string, _format = nil)
return Date.orig_parse(_string) unless _format
Date.strptime(_string, Date::DATE_FORMATS[_format])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment