Skip to content

Instantly share code, notes, and snippets.

@devn
Created May 22, 2013 15:56
Show Gist options
  • Save devn/5628690 to your computer and use it in GitHub Desktop.
Save devn/5628690 to your computer and use it in GitHub Desktop.
(defprotocol Coercable
"Coerce Ruby objects to Clojure types"
(clj [this] "Coerce a Ruby object to its Clojure representation"))
(extend-protocol Coercable
org.jruby.RubyString
(clj [this] (str this)))
(extend-protocol Coercable
java.lang.Long
(clj [this] this))
(extend-protocol Coercable
java.lang.String
(clj [this] this))
(extend-protocol Coercable
org.jruby.RubyFixnum
(clj [this] (.getLongValue this)))
(extend-protocol Coercable
org.jruby.RubyArray
(clj [this] (mapv clj (vec (.toJavaArray this)))))
(extend-protocol Coercable
org.jruby.RubySymbol
(clj [this] (keyword (str this))))
(extend-protocol Coercable
org.jruby.RubyHash
(clj [this] (zipmap (mapv clj (.keys this))
(mapv clj (.values this)))))
(clj (_eval "{:a => 1, :b => 'c', :x => [1,2,3]}"))
;; => {:x [1 2 3], :b "c", :a 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment