From fab35bc3bb11e17f1859d19b306948c6395adb16 Mon Sep 17 00:00:00 2001 From: Tikhon Botchkarev Date: Tue, 29 Mar 2016 00:32:48 -0400 Subject: [PATCH] Add the option to use a modify the data beint sent by a webhook with a proc object --- lib/god/contacts/webhook.rb | 29 ++++++++++++++++++----------- test/test_webhook.rb | 14 ++++++++++++++ 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/lib/god/contacts/webhook.rb b/lib/god/contacts/webhook.rb index 240ec872..ec1f5e05 100644 --- a/lib/god/contacts/webhook.rb +++ b/lib/god/contacts/webhook.rb @@ -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' @@ -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) diff --git a/test/test_webhook.rb b/test/test_webhook.rb index 3725ff14..bc8ad91c 100644 --- a/test/test_webhook.rb +++ b/test/test_webhook.rb @@ -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