Class: Lita::Handlers::Howdoi

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

Constant Summary collapse

SEARCH_URL =
"http://stackoverflow.com/search"

Instance Method Summary collapse

Instance Method Details

#howdoi(chat) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lita/handlers/howdoi.rb', line 18

def howdoi(chat)
  search_query = chat.matches[0].last.split.join("+")
  first_result = search_stack_overflow_for(search_query).first

  if first_result
    html = Nokogiri.HTML(http.get(first_result).body)
    answer = html.at_css(".answer")

    if answer
      instruction = answer.css("pre").children.
        collect(&:content).
        join(" " * 5 + '-' * 50 + "\n") ||
        answer.at_css("code").content

      if !instruction.empty?
        chat.reply "```\n#{instruction}```"
      else
        chat.reply "```\n#{answer.at_css('.post-text').content}```"
      end
    end
  else
    chat.reply "Sorry, couldn't find any help with that topic"
  end
end

#search_stack_overflow_for(search_query) ⇒ Object



12
13
14
15
16
# File 'lib/lita/handlers/howdoi.rb', line 12

def search_stack_overflow_for(search_query)
  page = http.get(SEARCH_URL, q: search_query).body
  html = Nokogiri.HTML(page)
  html.css('.result-link a').map { |link| "http://stackoverflow.com#{link[:href]}" }
end