PageRenderTime 0ms CodeModel.GetById 40ms app.highlight 5ms RepoModel.GetById 35ms app.codeStats 0ms

/01_ruby/03_web/duck.rb

https://github.com/Ronovan/ruby-rails-jumpstart
Ruby | 33 lines | 24 code | 8 blank | 1 comment | 0 complexity | f7679ff9afc80dbb3e5c897259d38dd3 MD5 | raw file
 1require 'open-uri'
 2require 'json'
 3
 4
 5BASE_URL = "http://api.duckduckgo.com/?format=json&pretty=1&q="     # remote API url
 6query     = "web services"                                          # query string
 7query_url = BASE_URL + URI.escape(query)                            # putting the 2 together
 8
 9
10puts " ======================================== "                   # fancy output
11puts "   #{query_url}"                                              # fancy output
12
13object = open(query_url) do |v|                                     # call the remote API
14  input = v.read                                                    # read the full response
15#  puts input                                                       # un-comment this to see the returned JSON magic
16  JSON.parse(input)                                                 # parse the JSON & return it from the block
17end
18
19puts " ======================================== "                   # fancy output
20puts "   #{object['Heading']}"
21puts "     #{object['Abstract']}"
22puts "     #{object['AbstractURL']}"
23puts " ---------------------------------------- "
24
25object['RelatedTopics'].each do |rt|                                # processing sub-elements
26  puts
27  puts "   * #{rt['Text']}"
28  puts "     #{rt['FirstURL']}"
29end
30
31puts                                                                # fancy output
32puts " ---------------------------------------- "
33puts " ======================================== "