ruby-rails-jumpstart /01_ruby/03_web/duck.rb

Language Ruby Lines 33
MD5 Hash f7679ff9afc80dbb3e5c897259d38dd3 Estimated Cost $538 (why?)
Repository https://github.com/Ronovan/ruby-rails-jumpstart.git View Raw File
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
require 'open-uri'
require 'json'


BASE_URL = "http://api.duckduckgo.com/?format=json&pretty=1&q="     # remote API url
query     = "web services"                                          # query string
query_url = BASE_URL + URI.escape(query)                            # putting the 2 together


puts " ======================================== "                   # fancy output
puts "   #{query_url}"                                              # fancy output

object = open(query_url) do |v|                                     # call the remote API
  input = v.read                                                    # read the full response
#  puts input                                                       # un-comment this to see the returned JSON magic
  JSON.parse(input)                                                 # parse the JSON & return it from the block
end

puts " ======================================== "                   # fancy output
puts "   #{object['Heading']}"
puts "     #{object['Abstract']}"
puts "     #{object['AbstractURL']}"
puts " ---------------------------------------- "

object['RelatedTopics'].each do |rt|                                # processing sub-elements
  puts
  puts "   * #{rt['Text']}"
  puts "     #{rt['FirstURL']}"
end

puts                                                                # fancy output
puts " ---------------------------------------- "
puts " ======================================== "
Back to Top