forked from joffotron/env-reservation-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcierge.rb
80 lines (66 loc) · 1.96 KB
/
concierge.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
require_relative 'reservation'
require "ostruct"
require 'time'
require 'active_support/core_ext/string'
require 'active_support/core_ext/time'
require 'aws-sdk-dynamodb'
class Concierge
def reserve(reservation:)
if reservation.start_time.nil?
cancel_reservation(reservation)
return
end
make_reservation(reservation)
end
def reservations
all_rows = dynamo.scan(table_name: ENV['DYNAMO_TABLE'])
saved = all_rows.items.map do |item|
p item
user = OpenStruct.new(name: item['user_name'], timezone: item['timezone'])
Reservation.new(
user: user,
environment: item['environment'],
start_time: try_date_parse(item['start_time']),
end_time: try_date_parse(item['end_time']),
comment: item['comment']
)
end
saved.select(&:current?)
end
private
def make_reservation(reservation)
item = {
environment: empty_check(reservation.environment),
start_time: empty_check(reservation.start_time&.rfc3339),
end_time: empty_check(reservation.end_time&.rfc3339),
user_name: empty_check(reservation.user_name),
timezone: empty_check(reservation.timezone),
comment: empty_check(reservation.comment)
}
dynamo.put_item(table_name: ENV['DYNAMO_TABLE'], item: item)
rescue Aws::DynamoDB::Errors::ServiceError => error
puts 'Unable to add reservation:'
puts error.message
end
def cancel_reservation(reservation)
dynamo.delete_item(
key: { 'environment' => reservation.environment},
table_name: ENV['DYNAMO_TABLE']
)
rescue Aws::DynamoDB::Errors::ServiceError => error
puts 'Unable to remove reservation:'
puts error.message
end
def dynamo
@dynamo ||= Aws::DynamoDB::Client.new
end
def try_date_parse(date_time)
date_time.to_datetime.in_time_zone
rescue
nil
end
def empty_check(string)
return nil if string.nil? || string.length == 0
string
end
end