Created
January 4, 2017 20:23
-
-
Save Dagnan/2a32e75759bad4e5c934da08bcebcdf0 to your computer and use it in GitHub Desktop.
Monkey patching Rails 3.2 to write datetimes with precision
This file contains hidden or 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
# config/initializers/time.rb | |
module ActiveRecord | |
module ConnectionAdapters | |
module Quoting | |
alias_method :old_quoted_date, :quoted_date | |
alias_method :old_quote, :quote | |
# In Rails 3.2 quoted_date does not have the column argument | |
def quoted_date(value, column = nil) | |
# Calls original method ; default in Rails 3.2 | |
return old_quoted_date(value) unless column | |
result = old_quoted_date(value) | |
# Just in case someone changes the :db format to include subsecond precision | |
return result if result.index('.') | |
# Will return value with micro seconds, letting mysql round the value | |
# according to the column length | |
"#{result}.#{value.usec}" | |
end | |
def quote(value, column = nil) | |
if value.is_a?(ActiveSupport::TimeWithZone) && column.try(:limit) && column.limit > 0 | |
return "'#{quoted_date(value, column)}'" | |
end | |
old_quote(value, column) | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment