#!/usr/bin/env ruby require "active_model" require "active_support/core_ext" # Checks the time is after|before|not after|not before given time. # # validates :next_alarm, time: { after: Time.now, not_after: 1.day.from_now } # # Use the :allow_nil key to skip validation in case the attribute value isn't set. # # validates :next_alarm, time: { after: Time.now, allow_nil: true } # class TimeValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if value.nil? && options[:allow_nil] { after: :>, before: :<, not_after: :<=, not_before: :>= }.each do |key, check| if target = options[key] record.errors.add attribute, :"#{ key }_time" unless value.try check, target end end end end