Skip to content

Instantly share code, notes, and snippets.

@dan-palmer
Last active August 29, 2015 14:23
Show Gist options
  • Save dan-palmer/afcd2ad9e4fc00669f0d to your computer and use it in GitHub Desktop.
Save dan-palmer/afcd2ad9e4fc00669f0d to your computer and use it in GitHub Desktop.
Repeating weekday incident SMS alert that triggers inbetween work hours.
require 'rubygems'
require 'active_support/time'
require 'clockwork'
require 'twilio-ruby'
require 'logger'
class WeekdayTimeKeeper
START_WORK_DAY = 10.hours.freeze
END_WORK_DAY = 17.hours.freeze
WORKING_HOURS = START_WORK_DAY..END_WORK_DAY.freeze
attr_reader :time
def initialize
can_perform_today? ? configure_for_today! : next_time!
end
def next_time!
@time = next_weekday + random_time_between_work_hours
end
def ready?
@time <= Time.now
end
private
def random_time_between_work_hours(range: WORKING_HOURS)
rand range
end
def can_perform_today?
WORKING_HOURS.cover?(starting_hours_minutes) || starting_hours_minutes < START_WORK_DAY
end
def configure_for_today!
todays_start_time = [START_WORK_DAY, starting_hours_minutes].max
todays_working_hours = todays_start_time..END_WORK_DAY
@time = Date.today + random_time_between_work_hours(range: todays_working_hours)
end
def starting_hours_minutes
cached_start_time.hour.hours + cached_start_time.min.minutes
end
def cached_start_time
@cached_start_time ||= Time.now
end
def next_weekday
tomorrow = Date.tomorrow
[tomorrow].tap { |a| a << 2.days if tomorrow.saturday? }.reduce(:+)
end
end
module FakeIncident
ACCOUNT_SID = ENV.fetch('twilio_account_sid').freeze
AUTH_TOKEN = ENV.fetch('twilio_auth_token').freeze
FROM_NUMBER = ENV.fetch('sms_from_number').freeze
TO_NUMBER = ENV.fetch('sms_to_number').freeze
SMS_BODY = \
'Something terrible has happened, all of the apps are breaking!'.freeze
def send_sms
client.account.messages.create from: FROM_NUMBER, to: TO_NUMBER, body: SMS_BODY
end
private
def client
@client ||= Twilio::REST::Client.new(ACCOUNT_SID, AUTH_TOKEN)
end
extend self
end
module FakeAlertCycle
def start
Clockwork.every 1.minute, 'fake-incident-sms.job' do
logger.info "Configured to send SMS at: #{time_keeper.time}"
if time_keeper.ready?
logger.info 'Sending a Fake Incident SMS..'
FakeIncident.send_sms
time_keeper.next_time!
end
end
end
private
def logger
@logger ||= Logger.new STDOUT
end
def time_keeper
@time_keeper ||= WeekdayTimeKeeper.new
end
extend self
end
FakeAlertCycle.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment