Created
April 18, 2019 11:55
-
-
Save kucaahbe/480a5d6ccec2db09288a62f1500a40cb to your computer and use it in GitHub Desktop.
Rails time comparison workaround
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
module RemoveTimePrecisionGranularity | |
def self.included(mod) | |
mod.class_eval do | |
extend ClassMethods | |
alias_method :orig_equals, :== | |
end | |
end | |
module ClassMethods | |
def equals_method_ignore_1_second_granularity! | |
alias_method :==, :__patched_eql? | |
end | |
def revert_to_original_equals_method! | |
alias_method :==, :orig_equals | |
end | |
end | |
# Use 1-second granularity when comparing times. | |
# See http://blog.solanolabs.com/rails-time-comparisons-devil-details-etc/ | |
def __patched_eql?(other) | |
to_i == other.to_i | |
end | |
end | |
class ActiveSupport::TimeWithZone | |
include RemoveTimePrecisionGranularity | |
end | |
class Time | |
include RemoveTimePrecisionGranularity | |
end | |
RSpec.configure do |config| | |
config.before :each, :ignore_ruby_time_precision do | |
ActiveSupport::TimeWithZone.equals_method_ignore_1_second_granularity! | |
Time.equals_method_ignore_1_second_granularity! | |
end | |
config.after :each, :ignore_ruby_time_precision do | |
ActiveSupport::TimeWithZone.revert_to_original_equals_method! | |
Time.revert_to_original_equals_method! | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment