Class: Marshmallow::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/god/contacts/hipchat.rb,
lib/god/contacts/campfire.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Connection

Returns a new instance of Connection.



19
20
21
22
# File 'lib/god/contacts/hipchat.rb', line 19

def initialize(options)
  raise "Required option :token not set." unless options[:token]
  @options = options
end

Instance Method Details

#base_urlObject



24
25
26
27
# File 'lib/god/contacts/hipchat.rb', line 24

def base_url
  scheme = @options[:ssl] ? 'https' : 'http'
  "#{scheme}://api.hipchat.com/v1/rooms"
end

#find_room_id_by_name(room) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/god/contacts/hipchat.rb', line 29

def find_room_id_by_name(room_name)
  url = URI.parse("#{base_url}/list?format=json&auth_token=#{@options[:token]}")
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true if @options[:ssl]

  req = Net::HTTP::Get.new(url.request_uri)
  req.set_content_type('application/json')

  res = http.request(req)
  case res
    when Net::HTTPSuccess
      rooms = JSON.parse(res.body)
      room = rooms['rooms'].select { |x| x['name'] == room_name }
      rooms.empty? ? nil : room.first['room_id'].to_i
    else
      raise res.error!
  end
end

#speak(room, message) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/god/contacts/hipchat.rb', line 48

def speak(room, message)
  room_id = find_room_id_by_name(room)
  puts "in spark: room_id = #{room_id}"
  raise "No such room: #{room}." unless room_id

  escaped_message = URI.escape(message)

  url = URI.parse("#{base_url}/message?message_format=text&format=json&auth_token=#{@options[:token]}&from=#{@options[:from]}&room_id=#{room}&message=#{escaped_message}")
  
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true if @options[:ssl]

  req = Net::HTTP::Post.new(url.request_uri)
  req.set_content_type('application/json')
  res = http.request(req)
  case res
    when Net::HTTPSuccess
      true
    else
      raise res.error!
  end
end