Paul Barry

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 ""
=> #<URI::HTTP:0x2adb22 URL:>
>> uri.scheme
=> "http"
=> ""
>> 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
user=> (def uri ( ""))
user=> (.getHost uri)

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 :scheme)
user=> (uri :host)
user=> (uri :path)
user=> (uri :query)
Posted in Technology | Topics Clojure