Class: Slackit

Inherits:
Object
  • Object
show all
Defined in:
lib/slackit.rb,
lib/slackit/version.rb

Overview

To follow

Constant Summary collapse

VERSION =
'1.1.10'

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Slackit

Returns a new instance of Slackit.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
# File 'lib/slackit.rb', line 12

def initialize(options = {})
    @webhook_url  = options[:webhook_url]
    @username     = options[:username]
    @channel      = options[:channel]
    @icon_emoji   = options[:icon_emoji]

    raise ArgumentError.new('Webhook URL required') if @webhook_url.nil?
end

Instance Method Details

#convert_to_json(json_string) ⇒ Object

Convery the string to json



58
59
60
61
62
63
64
# File 'lib/slackit.rb', line 58

def convert_to_json(json_string)
    begin
        return JSON.parse(json_string)
    rescue JSON::ParserError
        raise ArgumentError.new('Invalid json')
    end
end

#send(text) ⇒ Object

Add an alias for backwards compatibility



35
36
37
# File 'lib/slackit.rb', line 35

def send(text)
    return send_message(text)
end

#send_attachment(attachment) ⇒ Object

Legacy attachments



42
43
44
45
# File 'lib/slackit.rb', line 42

def send_attachment(attachment)
    payload = { 'attachments' => [ convert_to_json(attachment) ] }
    return send_payload(payload)
end

#send_block(block) ⇒ Object

New shiney blocks



50
51
52
53
# File 'lib/slackit.rb', line 50

def send_block(block)
    payload = convert_to_json(block)
    return send_payload(payload)
end

#send_message(text) ⇒ Object

Raw message



24
25
26
27
28
29
30
# File 'lib/slackit.rb', line 24

def send_message(text)
    text = text.gsub('\\n', "\n") # ensure newlines are not escaped

    payload = { 'text' => text }

    return send_payload(payload)
end

#send_payload(payload) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/slackit.rb', line 66

def send_payload(payload)
    headers = { 'Content-Type' => 'application/json' }

    # Add the additional payload items
    payload['icon_emoji'] ||= @icon_emoji
    payload['username'] ||= @username
    payload['channel'] ||= @channel

    begin
        response = HTTParty.post(@webhook_url, body: payload.to_json, headers: headers)

        return true if response.code == 200

        raise response
    rescue HTTParty::Error, SocketError => e
        raise e
    end
end