Sha256: 0e9625d19b81625e64c153c3abbe139919e81e884aeb2f5c6be4a0a20816d284

Contents?: true

Size: 1.03 KB

Versions: 5

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

# https://guides.rubyonrails.org/active_record_validations.html#validates-with
module Dsu
  module Validators
    class TimeValidator < ActiveModel::Validator
      def validate(record)
        raise 'options[:fields] is not defined.' unless options.key? :fields
        raise 'options[:fields] is not an Array.' unless options[:fields].is_a? Array
        raise 'options[:fields] elements are not Symbols.' unless options[:fields].all?(Symbol)

        options[:fields].each do |field|
          time = record.send(field)

          if time.nil?
            record.errors.add(field, :blank)
            next
          end

          unless time.is_a?(Time)
            record.errors.add(field, 'is the wrong object type. ' \
                                     "\"Time\" was expected, but \"#{time.class}\" was received.")
            next
          end

          if time.utc?
            record.errors.add(field, 'is not in localtime format.')
            next
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dsu-0.1.0.alpha.5 lib/dsu/validators/time_validator.rb
dsu-0.1.0.alpha.4 lib/dsu/validators/time_validator.rb
dsu-0.1.0.alpha.3 lib/dsu/validators/time_validator.rb
dsu-0.1.0.alpha.2 lib/dsu/validators/time_validator.rb
dsu-0.1.0.alpha.1 lib/dsu/validators/time_validator.rb