Class: AwsLogs::Since

Inherits:
Object
  • Object
show all
Defined in:
lib/aws_logs/since.rb

Constant Summary collapse

DEFAULT =
10.minutes.to_i
ISO8601_REGEXP =
/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/
FRIENDLY_REGEXP =
/(\d+)(\w+)/

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Since

Returns a new instance of Since.


8
9
10
# File 'lib/aws_logs/since.rb', line 8

def initialize(str)
  @str = str
end

Instance Method Details

#find_match(regexp) ⇒ Object


54
55
56
57
58
59
60
# File 'lib/aws_logs/since.rb', line 54

def find_match(regexp)
  md = @str.match(regexp)
  if md
    number, unit = md[1].to_i, md[2]
  end
  [number, unit]
end

#friendly_format?Boolean

Returns:

  • (Boolean)

34
35
36
# File 'lib/aws_logs/since.rb', line 34

def friendly_format?
  !!@str.match(FRIENDLY_REGEXP)
end

#friendly_secondsObject


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/aws_logs/since.rb', line 38

def friendly_seconds
  number, unit = find_match(FRIENDLY_REGEXP)
  unless number && unit
    puts warning
    return DEFAULT
  end

  meth = shorthand(unit)
  if number.respond_to?(meth)
    number.send(meth).to_i
  else
    puts warning
    return DEFAULT
  end
end

#iso8601_format?Boolean

Returns:

  • (Boolean)

24
25
26
# File 'lib/aws_logs/since.rb', line 24

def iso8601_format?
  !!@str.match(ISO8601_REGEXP)
end

#iso8601_secondsObject


28
29
30
31
# File 'lib/aws_logs/since.rb', line 28

def iso8601_seconds
  # https://stackoverflow.com/questions/3775544/how-do-you-convert-an-iso-8601-date-to-a-unix-timestamp-in-ruby
  Time.iso8601(@str.sub(/ /,'T')).to_i
end

#shorthand(k) ⇒ Object

s - seconds m - minutes h - hours d - days w - weeks


71
72
73
74
75
76
77
78
79
80
# File 'lib/aws_logs/since.rb', line 71

def shorthand(k)
  map = {
    s: :seconds,
    m: :minutes,
    h: :hours,
    d: :days,
    w: :weeks,
  }
  map[k.to_sym] || k
end

#to_iObject


12
13
14
15
16
17
18
19
20
21
# File 'lib/aws_logs/since.rb', line 12

def to_i
  if iso8601_format?
    iso8601_seconds
  elsif friendly_format?
    friendly_seconds
  else
    puts warning
    return DEFAULT
  end
end

#warningObject


62
63
64
# File 'lib/aws_logs/since.rb', line 62

def warning
  "WARN: since is not in a supported format. Falling back to 10m".color(:yellow)
end