class God::Contacts::Slack

Attributes

channel[RW]
emoji[RW]
format[RW]
notify_channel[RW]
url[RW]
username[RW]
channel[RW]
emoji[RW]
format[RW]
notify_channel[RW]
url[RW]
username[RW]

Public Instance Methods

api_url() click to toggle source
# File lib/god/contacts/slack.rb, line 64
def api_url
  URI.parse arg(:url)
end
notify(message, time, priority, category, host) click to toggle source
# File lib/god/contacts/slack.rb, line 52
def notify(message, time, priority, category, host)
  text = text({
    :message => message,
    :time => time,
    :priority => priority,
    :category => category,
    :host => host
  })

  request(text)
end
request(text) click to toggle source
# File lib/god/contacts/slack.rb, line 68
def request(text)
  http = Net::HTTP.new(api_url.host, api_url.port)
  http.use_ssl = true

  req = Net::HTTP::Post.new(api_url.request_uri)
  req.body = {
    :link_names => 1,
    :text => text,
    :channel => arg(:channel)
  }.tap { |payload|
    payload[:username] = arg(:username) if arg(:username)
    payload[:icon_emoji] = arg(:emoji) if arg(:emoji)
  }.to_json

  res = http.request(req)

  case res
    when Net::HTTPSuccess
      self.info = "successfully notified slack on channel #{arg(:channel)}"
    else
      self.info = "failed to send webhook to #{arg(:url)}: #{res.error!}"
  end
rescue Object => e
  applog(nil, :info, "failed to send webhook to #{arg(:url)}: #{e.message}")
  applog(nil, :debug, e.backtrace.join("\n"))
end
text(data) click to toggle source
# File lib/god/contacts/slack.rb, line 37
def text(data)
  text = ""
  text << "<!channel> " if arg(:notify_channel)

  if RUBY_VERSION =~ /^1\.8/
    text << arg(:format).gsub(/%\{(\w+)\}/) do |match|
      data[$1.to_sym]
    end
  else
    text << arg(:format) % data
  end

  text
end
valid?() click to toggle source
# File lib/god/contacts/slack.rb, line 29
def valid?
  valid = true
  valid &= complain("Attribute 'url' must be specified", self) unless arg(:url)
  valid
end