Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions lib/god/contacts/webhook.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Send a notice to a webhook.
#
# url - The String webhook URL.
# format - The Symbol format [ :form | :json ] (default: :form).
# url - The String webhook URL.
# format - The Symbol format [ :form | :json ] (default: :form).
# process_data - The optional Proc that returns a custom data object to send to the webhook.

require 'net/http'
require 'uri'
Expand All @@ -16,28 +17,34 @@ module Contacts

class Webhook < Contact
class << self
attr_accessor :url, :format
attr_accessor :url, :format, :process_data
end

self.format = :form
self.process_data = nil

def valid?
valid = true
valid &= complain("Attribute 'url' must be specified", self) unless arg(:url)
valid &= complain("Attribute 'format' must be one of [ :form | :json ]", self) unless [:form, :json].include?(arg(:format))
valid &= complain("Attribute 'process_data' must be a proc object if defined ", self) unless arg(:process_data).nil? || arg(:process_data).is_a?(Proc)
valid
end

attr_accessor :url, :format
attr_accessor :url, :format, :process_data

def notify(message, time, priority, category, host)
data = {
:message => message,
:time => time,
:priority => priority,
:category => category,
:host => host
}
if arg(:process_data)
data = arg(:process_data).call(message, time, priority, category, host)
else
data = {
:message => message,
:time => time,
:priority => priority,
:category => category,
:host => host
}
end

uri = URI.parse(arg(:url))
http = Net::HTTP.new(uri.host, uri.port)
Expand Down
14 changes: 14 additions & 0 deletions test/test_webhook.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,18 @@ def test_notify_with_url_containing_query_parameters

@webhook.notify('msg', Time.now, 'prio', 'cat', 'host')
end

def test_notify_with_process_data_callback
data_to_send = {:processed => true}
data_callback = proc do |message, time, priority, category, host|
data_to_send
end

@webhook.url = 'http://example.com/switch'
@webhook.format = :json
@webhook.process_data = data_callback
Net::HTTP.any_instance.expects(:request).with {|req| req.body == data_to_send.to_json }.returns(Net::HTTPSuccess.new('a', 'b', 'c'))

@webhook.notify('msg', Time.now, 'prio', 'cat', 'host')
end
end