Class: ICU::Date

Inherits:
Object
  • Object
show all
Defined in:
lib/icu_utils/date.rb

Overview

Reproduce some of the functionality of validates_timeliness, a gem no longer maintained.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(date, constraints = {}) ⇒ Date

Returns a new instance of Date.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/icu_utils/date.rb', line 6

def initialize(date, constraints={})
  @reasons = []
  if @date = to_date(date)
    @constraints = constraints.each_with_object({}) do |(k,v), h|
      if %i[after on_or_after before on_or_before].include?(k)
        unless h[k] = to_date(v)
          raise ArgumentError.new("invalid date specified for #{k} constraint")
        end
      else
        raise ArgumentError.new("invalid date constraint #{k}")
      end
    end
  else
    @reasons.push "errors.messages.invalid_date"
  end
end

Instance Attribute Details

#dateObject (readonly)

Returns the value of attribute date.



4
5
6
# File 'lib/icu_utils/date.rb', line 4

def date
  @date
end

#reasonsObject (readonly)

Returns the value of attribute reasons.



4
5
6
# File 'lib/icu_utils/date.rb', line 4

def reasons
  @reasons
end

Instance Method Details

#valid?Boolean

Returns:

  • (Boolean)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/icu_utils/date.rb', line 23

def valid?
  valid = true
  if @date
    if valid && @constraints[:after] && @date <= @constraints[:after]
      valid = false
      @reasons.push "errors.messages.after"
      @reasons.push restriction: @constraints[:after].to_s
    end
    if valid && @constraints[:before] && @date >= @constraints[:before]
      valid = false
      @reasons.push "errors.messages.before"
      @reasons.push restriction: @constraints[:before].to_s
    end
    if valid && @constraints[:on_or_after] && @date < @constraints[:on_or_after]
      valid = false
      @reasons.push "errors.messages.on_or_after"
      @reasons.push restriction: @constraints[:on_or_after].to_s
    end
    if valid && @constraints[:on_or_before] && @date > @constraints[:on_or_before]
      valid = false
      @reasons.push "errors.messages.on_or_before"
      @reasons.push restriction: @constraints[:on_or_before].to_s
    end
  else
    valid = false
  end
  valid
end