Skip to content

Instantly share code, notes, and snippets.

@Dagnan
Created January 4, 2017 20:23
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 Dagnan/2a32e75759bad4e5c934da08bcebcdf0 to your computer and use it in GitHub Desktop.
Save Dagnan/2a32e75759bad4e5c934da08bcebcdf0 to your computer and use it in GitHub Desktop.
Monkey patching Rails 3.2 to write datetimes with precision
# 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