/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

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