Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Simplify "Unified Update Model" lab

* Use built-in "slurp" instead of custom-defined "request"
* Include source to "url-encode" in the lab
  • Loading branch information...
commit d0ba1f1bed184acdfcec98de837c9a59e7c1eb8e 1 parent 886ceb7
@stuartsierra stuartsierra authored
Showing with 7 additions and 12 deletions.
  1. +5 −3 src/labs/unified_update_model.clj
  2. +2 −9 src/solutions/fight.clj
View
8 src/labs/unified_update_model.clj
@@ -119,17 +119,19 @@
namespaces:"
(code "(use '[clojure.data.json :only (read-json)])")]
[:ol
- [:li "The " (c request) " function takes a URL string and returns a map of
+ [:li "The " (c slurp) " function takes a URL or filename string and returns a String of
response data. Try it a the REPL to see how it works."]
[:li "To get google search results, you will need the following URL prefix:"
(source google-search-base)]
[:li "Since some interesting searches are multiword, you will want
to " (c url-encode) " them: "
- (repl-showme (url-encode "two words"))]
+ (repl-code (url-encode "two words"))]
+ [:li "The " (c url-encode) " function is a thin wrapper around Java's " (c URLEncoder)
+ (showme url-encode)]
[:li "The search results are returned as JSON. The" (c read-json) " function
converts JSON into Clojure data. Test it at the REPL:"
(repl-showme (read-json "{\"foo\" : [1, 2]}"))]
- [:li "Using the functions " (c request) ", " (c url-encode) ", and "
+ [:li "Using the functions " (c slurp) ", " (c url-encode) ", and "
(c read-json) ", you can write an " (c estimated-hits-for) " function
that returns the estimated hits for a search term:"
(showme estimated-hits-for)]
View
11 src/solutions/fight.clj
@@ -1,7 +1,6 @@
(ns solutions.fight
(:use [clojure.data.json :only (read-json)])
- (:import (java.net URL URLEncoder)
- (java.io BufferedReader InputStreamReader)))
+ (:import (java.net URL URLEncoder)))
(def google-search-base
"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=")
@@ -9,15 +8,9 @@
(defn url-encode [q]
(URLEncoder/encode q "UTF-8"))
-(defn request [address]
- (let [url (URL. address)]
- (with-open [stream (. url (openStream))]
- (let [buf (BufferedReader. (InputStreamReader. stream))]
- (apply str (line-seq buf))))))
-
(defn estimated-hits-for
[term]
- (let [http-response (request (str google-search-base (url-encode term)))
+ (let [http-response (slurp (str google-search-base (url-encode term)))
json-response (read-json http-response)]
(Long/parseLong (get-in json-response [:responseData :cursor :estimatedResultCount]))))
Please sign in to comment.
Something went wrong with that request. Please try again.