Ruby's URI for Clojure

December 13, 2008

Ruby has a nice library for working with URIs:

$ irb --simple-prompt
>> require 'uri'
=> true
>> uri = URI.parse "http://www.google.com/search?q=clojure"
=> #<URI::HTTP:0x2adb22 URL:http://www.google.com/search?q=clojure>
>> uri.scheme
=> "http"
>> uri.host
=> "www.google.com"
>> uri.path
=> "/search"
>> uri.query
=> "q=clojure"

So how do we get this same functionality in Clojure? Well, turns out Java has a library that is functionally equivalent to Ruby's. The downsize is it entirely very Java-ish:

~/src/clojure $ java -jar clojure.jar
Clojure
user=> (def uri (java.net.URI. "http://www.google.com/search?q=clojure"))
#'user/uri
user=> (.getHost uri)
"www.google.com"

It would be nice to use this in a more idiomatic Clojure way, but one of the principals of Clojure is to provide access to all the Java libraries without having to write Clojure wrappers for all of them. So one way to accomplish this is with the clojure bean function. It takes a java bean and returns a Map with the values for all of the getters in the bean. We can use this to use the URI in an idiomatic way that looks more like the Ruby version:

user=> (def uri (bean uri))
#'user/uri
user=> (uri :scheme)
"http"
user=> (uri :host)
"www.google.com"
user=> (uri :path)
"/search"
user=> (uri :query)
"q=clojure" 

Posted in Technology | Tags Clojure

Comments Comments Feed

1.
There are many people like to searching the famous brand shoes
online.
Nike Air Max
is always the best choice and you will fall in love when the first sight.As the most sought-after products,
the famous brand shoes
are not only fashionable but also practical.Nike Air Max which is one of the hottest shoes in the summer are available in a variety of styles, colors and materials.
Nike Air Max shoes
are designed for yourself.You can pick up a pair now at www.online268.com.

# Posted By online268 on Wednesday, September 1 2010 at 4:49 PM

2.
Cheap nfl jerseys are your best choice, and retail nfl apparell and drop shipping are accepted as well. Grade cheap nfl sports jerseys,Competitive price and Best service, We do hope nfl jerseys usa to do long-term business with every clients and help you improvefootball jerseys more benefit from your market.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:29 PM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)