class FDE::Slack::Message

Constants

BLUE
GREEN
RED
RETRY_LIMIT
TOO_MANY_REQUESTS_STATUS_CODE
YELLOW

Attributes

author[RW]
color[RW]
fields[RW]
retries[R]
title[RW]
username[RW]

Public Class Methods

new(title, fields, options = {}) click to toggle source
# File lib/slack/message.rb, line 25
def initialize(title, fields, options = {})
  @title = title
  @fields = fields
  if options[:title_link]
    @title_link = options[:title_link]
  end
  if options[:username]
    @username = options[:username] || 'FDE Slack Notifier'
  end
  if options[:author]
    @author = options[:author]
  end
  if options[:footer]
    @footer = options[:footer]
  end

  @retries = 0
end

Public Instance Methods

add_field(field) click to toggle source
# File lib/slack/message.rb, line 68
def add_field(field)
  @fields << field.to_h
end
deliver(channel, level: :info) click to toggle source
# File lib/slack/message.rb, line 44
def deliver(channel, level: :info)
  send(level, channel)
end
error(channel) click to toggle source
# File lib/slack/message.rb, line 63
def error(channel)
  @color = RED
  send_message(channel)
end
info(channel) click to toggle source
# File lib/slack/message.rb, line 48
def info(channel)
  @color = BLUE
  send_message(channel)
end
success(channel) click to toggle source
# File lib/slack/message.rb, line 53
def success(channel)
  @color = GREEN
  send_message(channel)
end
warning(channel) click to toggle source
# File lib/slack/message.rb, line 58
def warning(channel)
  @color = YELLOW
  send_message(channel)
end

Private Instance Methods

attachment_hash() click to toggle source
# File lib/slack/message.rb, line 104
def attachment_hash
  hash = {
    fallback: @title,
    ts: Time.now.to_i,
    color: @color,
    fields: @fields
  }
  hash.merge!(@author.to_h)
  hash.merge!(@footer.to_h)
  hash.merge!(@title_link.to_h)
  hash
end
message_hash() click to toggle source
# File lib/slack/message.rb, line 100
def message_hash
  { attachments: [ attachment_hash ] }
end
send_message(channel) click to toggle source
# File lib/slack/message.rb, line 74
def send_message(channel)
  notifier = ::Slack::Notifier.new(
    FDE::Slack::Notification.config.webhook,
    channel: channel,
    username: @username
  ) do
    # configure Slack Notifier gem to use our custom HTTPClient
    # see https://github.com/stevenosloan/slack-notifier#custom-http-client
    http_client FDE::Slack::Util::HTTPClient
  end

  begin 
    notifier.ping message_hash
  rescue FDE::Slack::APIError => api_error
    # TooManyRequests, Slack Rate Limit
    if api_error.response.code == TOO_MANY_REQUESTS_STATUS_CODE && @retries < RETRY_LIMIT
      timeout = api_error.response.header['Retry-After'].to_i
      sleep(timeout) if timeout
      @retries += 1
      retry
    end
    raise api_error, message_hash: message_hash

  end
end