Sha256: 920f040756ec9070c2e44b5a3522dcbe92df111c46e663d63d74f6e97c84bdc8

Contents?: true

Size: 1.15 KB

Versions: 7

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

module Normalizy
  module Filters
    module Date
      class << self
        def call(input, options = {})
          if input.is_a?(String)
            return input if input.blank?

            Time.use_zone(time_zone(options)) do
              input = Time.zone.strptime(input, format(options))
            end
          end

          if input.is_a?(Time) || input.is_a?(DateTime)
            input = input.beginning_of_day if options[:adjust] == :begin
            input = input.end_of_day       if options[:adjust] == :end
          end

          input
        rescue ArgumentError
          options[:object].errors.add options[:attribute], error_message(input, options)
        end

        private

        def error_message(input, options)
          I18n.t options[:attribute], scope: [
            'normalizy.errors.date', options[:object].class.name.underscore
          ], value: input, default: '%{value} is an invalid date.'
        end

        def format(options)
          options.fetch :format, '%F'
        end

        def time_zone(options)
          options.fetch :time_zone, 'UTC'
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
normalizy-1.3.0 lib/normalizy/filters/date.rb
normalizy-1.2.0 lib/normalizy/filters/date.rb
normalizy-1.1.1 lib/normalizy/filters/date.rb
normalizy-1.1.0 lib/normalizy/filters/date.rb
normalizy-1.0.1 lib/normalizy/filters/date.rb
normalizy-1.0.0 lib/normalizy/filters/date.rb
normalizy-0.2.0 lib/normalizy/filters/date.rb