diff --git a/lib/timex_datalink_client/protocol_7/eeprom/calendar/event.rb b/lib/timex_datalink_client/protocol_7/eeprom/calendar/event.rb index 6cc1a33..33285c5 100644 --- a/lib/timex_datalink_client/protocol_7/eeprom/calendar/event.rb +++ b/lib/timex_datalink_client/protocol_7/eeprom/calendar/event.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_model" + require "timex_datalink_client/helpers/lsb_msb_formatter" class TimexDatalinkClient @@ -7,16 +9,23 @@ class Protocol7 class Eeprom class Calendar class Event + include ActiveModel::Validations include Helpers::LsbMsbFormatter FIVE_MINUTES_SECONDS = 300 - attr_accessor :time, :phrase + validates :time, comparison: { + greater_than_or_equal_to: :device_time, + message: "%{value} must be greater or equal to device time!" + } + + attr_accessor :time, :phrase, :device_time # Create an Event instance. # # @param time [::Time] Time of event. # @param phrase [Array] Phrase for event. + # @raise [ActiveModel::ValidationError] One or more model values are invalid. # @return [Event] Event instance. def initialize(time:, phrase:) @time = time @@ -24,6 +33,10 @@ def initialize(time:, phrase:) end def time_formatted(device_time) + @device_time = device_time + + validate! + device_time_midnight = Time.new(device_time.year, device_time.month, device_time.day) seconds = (time - device_time_midnight).to_i five_minutes = seconds / FIVE_MINUTES_SECONDS diff --git a/spec/lib/timex_datalink_client/protocol_7/eeprom/calendar/event_spec.rb b/spec/lib/timex_datalink_client/protocol_7/eeprom/calendar/event_spec.rb index d303214..aa5ff21 100644 --- a/spec/lib/timex_datalink_client/protocol_7/eeprom/calendar/event_spec.rb +++ b/spec/lib/timex_datalink_client/protocol_7/eeprom/calendar/event_spec.rb @@ -43,5 +43,16 @@ it { should eq([0x7e, 0x0f]) } end + + context "when time is 2021-12-10 15:28:15" do + let(:time) { Time.utc(2021, 12, 23, 18, 30, 20) } + + it do + expect { phrase_value }.to raise_error( + ActiveModel::ValidationError, + "Validation failed: Time 2021-12-23 18:30:20 UTC must be greater or equal to device time!" + ) + end + end end end