From 0c6ed63e54b0d0230eda01dc504359a9ef44136e Mon Sep 17 00:00:00 2001 From: Nathaniel Watts <1141717+thewatts@users.noreply.github.com> Date: Fri, 22 Oct 2021 17:12:36 -0500 Subject: [PATCH] Add custom comparison for Montrose::Schedule In our application using Montrose, we have some instances where we want to be able to check to see if a schedule has changed. The specific use case for us is with a Rails model that is serializing a schedule - we want to be able to know if the schedule itself has changed, ie: `event.schedule_changed? #=> false` The same attributes may be assigned for the schedule's configuration - but Rails thinks that the schedule has changed b/c it's comparing the objects themselves instead of the underlying recurrence configurations. This commit overloads `Montrose::Schedule#==` so that schedules can be compared against each other within the context of their configurations. --- lib/montrose/schedule.rb | 8 ++++++++ spec/montrose/schedule_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/montrose/schedule.rb b/lib/montrose/schedule.rb index aaa3c6a..6ec1565 100644 --- a/lib/montrose/schedule.rb +++ b/lib/montrose/schedule.rb @@ -169,6 +169,14 @@ def inspect "#<#{self.class}:#{object_id.to_s(16)} #{to_a.inspect}>" end + def ==(other) + if !other.is_a?(self.class) && !other.is_a?(Array) + super + else + to_a == other.to_a + end + end + private def active_enums(enums) diff --git a/spec/montrose/schedule_spec.rb b/spec/montrose/schedule_spec.rb index 1573a1b..4394533 100644 --- a/spec/montrose/schedule_spec.rb +++ b/spec/montrose/schedule_spec.rb @@ -337,4 +337,27 @@ _(array).must_equal [{"every" => "month"}, {"every" => "day"}] end end + + describe "#==" do + before do + schedule << {every: :month} + schedule << {every: :day} + end + + it "compares two schedules against each other" do + identical_other = new_schedule.tap do |schedule| + schedule << {every: :month} + schedule << {every: :day} + end + + different_other = new_schedule.tap do |schedule| + schedule << {every: :month} + schedule << {every: :day} + schedule << {every: :year} + end + + _(schedule).must_equal identical_other + _(schedule).wont_equal different_other + end + end end