Class: Datemath::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/datemath/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Initialize



6
7
8
9
# File 'lib/datemath/parser.rb', line 6

def initialize(text)
  @text = text
  @units = ['y', 'M', 'w', 'd', 'h', 'm', 's', 'ms']
end

Instance Method Details

#parse(round_up = false) ⇒ DateTime

Parses a datemath string to DateTime

Parameters:

  • text (String)
  • round_up (Boolean) (defaults to: false)

Returns:

  • (DateTime)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/datemath/parser.rb', line 16

def parse(round_up = false)
  return nil unless @text

  time = nil
  math_string = ''
  index = nil
  parse_string = nil

  if (@text[0, 3] == 'now') 
    time = DateTime.now
    math_string = @text['now'.length..@text.length]
  else
    index = @text.index('||')
    if index.nil?
      parse_string = @text
      math_string = '' 
    else
      parse_string = @text[0, index]
      math_string = @text[(index + 2)..@text.length]
    end
    time = DateTime.parse(parse_string) rescue nil
  end

  return time if math_string == nil || math_string == '' || time.nil?
  parse_date_math(math_string, time, round_up)
end