Last active
December 17, 2015 15:09
-
-
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
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
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