File: slack-notifier.rb

package info (click to toggle)
ruby-slack-notifier 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 288 kB
  • sloc: ruby: 1,076; makefile: 5
file content (59 lines) | stat: -rw-r--r-- 1,398 bytes parent folder | download
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
# frozen_string_literal: true

require "uri"
require "json"

require_relative "slack-notifier/util/http_client"
require_relative "slack-notifier/util/link_formatter"
require_relative "slack-notifier/util/escape"
require_relative "slack-notifier/payload_middleware"
require_relative "slack-notifier/config"

module Slack
  class Notifier
    attr_reader :endpoint

    def initialize webhook_url, options={}, &block
      @endpoint = URI.parse webhook_url

      config.http_client(options.delete(:http_client)) if options.key?(:http_client)
      config.defaults options
      config.instance_exec(&block) if block_given?

      middleware.set config.middleware
    end

    def config
      @_config ||= Config.new
    end

    def ping message, options={}
      if message.is_a?(Hash)
        options = message
      else
        options[:text] = message
      end

      post options
    end

    def post payload={}
      params  = {}
      client  = payload.delete(:http_client) || config.http_client
      payload = config.defaults.merge(payload)

      params[:http_options] = payload.delete(:http_options) if payload.key?(:http_options)

      middleware.call(payload).map do |pld|
        params[:payload] = pld.to_json
        client.post endpoint, params
      end
    end

    private

      def middleware
        @middleware ||= PayloadMiddleware::Stack.new(self)
      end
  end
end