Class: Lita::Handlers::OnewheelWolframAlpha

Inherits:
Handler
  • Object
show all
Defined in:
lib/lita/handlers/onewheel_wolfram_alpha.rb

Instance Method Summary collapse

Instance Method Details

#build_uri(query) ⇒ Object



70
71
72
73
# File 'lib/lita/handlers/onewheel_wolfram_alpha.rb', line 70

def build_uri(query)
  uri = config.api_uri.sub '[query]', CGI::escape(query)
  uri.sub '[appid]', config.app_id
end

#handle_wolfram_query(response) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/lita/handlers/onewheel_wolfram_alpha.rb', line 12

def handle_wolfram_query(response)
  unless config.app_id and config.api_uri
    Lita.logger.error 'lita-onewheel-wolfram-alpha: Configuration error!'
    return
  end
  query = response.matches[0][0]

  post_script = ''

  if matches = query.match(/\<(.*)\>/)
    query.gsub! /\<#{matches[1]}\>/, ''
    post_script = " #{matches[1]}"
  end

  api_response = make_api_call query
  reply = parse_response api_response, query
  reply += post_script
  Lita.logger.debug "lita-onewheel-wolfram-alpha: Replying with #{reply}"
  response.reply reply
end

#make_api_call(query) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/lita/handlers/onewheel_wolfram_alpha.rb', line 62

def make_api_call(query)
  Lita.logger.debug "lita-onewheel-wolfram-alpha: Making api call for #{query}"
  uri = build_uri query
  response = RestClient.get(uri)
  Lita.logger.debug 'lita-onewheel-wolfram-alpha: ' + response.to_s
  Nokogiri::XML response.to_s
end

#parse_response(noko_doc, query) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/lita/handlers/onewheel_wolfram_alpha.rb', line 33

def parse_response(noko_doc, query)
  success_node = noko_doc.xpath('queryresult').attribute('success')
  Lita.logger.debug "lita-onewheel-wolfram-alpha: Success attr: #{success_node.to_s}"

  # No sense parsing if we didn't have success.
  if success_node.to_s == 'true'

    pods = noko_doc.xpath('//pod')
    Lita.logger.debug "lita-onewheel-wolfram-alpha: Pod title: #{pods[1].attribute('title').to_s}"

    title = pods[1].attribute('title').to_s
    if title == 'Plot'  # Plot is a graph, grab the image.
      pods[1].xpath('//img')[1].attribute('src').to_s
    else  # Plaintext seems to work well for, say, Definition.
      rid_thee_of_extras pods[1].xpath('//plaintext')[1].child.to_s
    end

  else
    ["Nope, no #{query} to see here.",
     "#{query}?",
     'What\'s that, now?'
     ].sample
  end
end

#rid_thee_of_extras(str) ⇒ Object



58
59
60
# File 'lib/lita/handlers/onewheel_wolfram_alpha.rb', line 58

def rid_thee_of_extras(str)
  str.gsub /\s+\|\s/, ' | '
end