Add Slack notifier (#5)

* Add slack notifier and service class to ping

* add global class method.

* update service class

* Finalize Slack notifier service

* Remove duplicate gem
This commit is contained in:
Andrew Fomera 2017-09-08 15:04:26 -05:00 committed by Justin Licata
parent 5b5fd06332
commit 658570920a
7 changed files with 72 additions and 0 deletions

@ -18,6 +18,7 @@ gem 'pg', '~> 0.18'
gem 'puma', '~> 3.7'
gem 'rails', '~> 5.1.1'
gem 'sass-rails', '~> 5.0'
gem 'slack-notifier', '~> 2.2.2'
gem 'turbolinks', '~> 5'
gem 'uglifier', '>= 1.3.0'
gem 'webpacker', '~> 2.0'

@ -202,6 +202,7 @@ GEM
selenium-webdriver (3.5.0)
childprocess (~> 0.5)
rubyzip (~> 1.0)
slack-notifier (2.2.2)
spring (2.0.2)
activesupport (>= 4.2)
spring-watcher-listen (2.0.1)
@ -270,6 +271,7 @@ DEPENDENCIES
rails (~> 5.1.1)
sass-rails (~> 5.0)
selenium-webdriver
slack-notifier (~> 2.2.2)
spring
spring-watcher-listen (~> 2.0.0)
turbolinks (~> 5)

@ -10,6 +10,10 @@ class Setting < ApplicationRecord
before_create :validate_only_one_setting_record
def self.global
first
end
private
def validate_only_one_setting_record

@ -0,0 +1,36 @@
module Notifiers
# SlackNotifier
#
# Send messages directly to your Slack channel.
class SlackNotifier
attr_reader(:message, :bot)
def initialize(message, bot = nil)
@message = message
@bot = bot
end
def notify!
raise('Slack URL is not set') unless slack_url.present?
notifier.ping(message, icon_url: icon_url)
end
private
def slack_url
@slack_url ||= Setting.global.slack_url
end
def notifier
Slack::Notifier.new(slack_url, username: bot_username)
end
def bot_username
bot.present? ? bot : 'storm'
end
def icon_url
'https://s3-us-west-2.amazonaws.com/storm-app/icon.png'
end
end
end

@ -1,4 +1,5 @@
FactoryGirl.define do
factory :setting do
slack_url('127.0.0.1/slack')
end
end

@ -12,4 +12,10 @@ class SettingTest < ActiveSupport::TestCase
assert(setting.save)
assert_not_nil(setting.encrypted_aws_secret)
end
test 'global' do
assert_nil(Setting.global)
setting = create(:setting)
assert_equal(setting, Setting.global)
end
end

@ -0,0 +1,22 @@
require('test_helper')
module Notifiers
# SlackNotifierTest
class SlackNotifierTest < ActiveSupport::TestCase
test 'bot_username' do
instance = Notifiers::SlackNotifier.new('msg')
assert_equal('storm', instance.send(:bot_username))
instance = Notifiers::SlackNotifier.new('msg', 'bot')
assert_equal('bot', instance.send(:bot_username))
end
test 'notify! without a Slack URL present' do
create(:setting, slack_url: nil)
assert_raise do
Notifiers::SlackNotifier.new('msg').notify!
end
end
end
end