December 13, 2008
$ 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"