Created
March 7, 2010 16:05
-
-
Save kyleburton/324438 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'java' | |
#require 'clojure-1.0.0.jar' | |
Dir["#{File.dirname(__FILE__)}/*.jar"].each { |jar| puts "requiring: #{jar}"; require jar } | |
import "clojure.lang.RT" | |
class CljHelper | |
def initialize *pkgs | |
@mappings = {} | |
@ns_map = RT.var "clojure.core", "ns-map" | |
@symbol = RT.var "clojure.core", "symbol" | |
@require = RT.var "clojure.core", "require" | |
pkgs.each do |pkg| | |
_import pkg | |
end | |
end | |
# TODO: can we import all of a package's symbols? | |
def _import pkg_name, sym=nil, sym_alais=nil | |
#pkg_name = pkg_name.gsub '-', '_' | |
puts "calling clojure.core/require #{pkg_name}" | |
@require.invoke @symbol.invoke(pkg_name) | |
if sym | |
sym_alias ||= sym | |
@mappings[sym_alias] = RT.var pkg_name, sym | |
return | |
end | |
puts "Importing all symbols from #{pkg_name}" | |
pkg = @symbol.invoke pkg_name | |
puts " => #{pkg}" | |
@ns_map.invoke(pkg).each do |sym,var| | |
#puts "importing: #{sym} => #{var}" | |
@mappings[sym.to_s] = var | |
end | |
end | |
def _invoke m, *args | |
fun = @mappings[m.to_s] || @mappings[m.to_s.gsub "_", "-"] | |
unless fun | |
raise "Error, no current binding for symbol=#{m}" | |
end | |
fun.invoke *args | |
end | |
def method_missing symbol, *args | |
_invoke symbol, *args | |
end | |
end | |
clj = CljHelper.new | |
puts "clj=#{clj}" | |
#clj._import 'clojure.core', 'prn' | |
clj._import 'clojure.core' | |
clj.prn "Hello Clojure, this is JRuby" | |
clj._invoke "prn", "Hello Clojure, this is JRuby" | |
# Further Work: | |
# Array.to_clj => convert to clojure array type or sequence, preferably immutable | |
# Map.to_clj => convert to clojure or java Map type, prefereably immutable | |
str_utils = CljHelper.new 'clojure.contrib.str-utils' | |
puts "Join: #{str_utils._invoke "str-join", ":", ["a", "b", "c"]}" | |
puts "Join: #{str_utils.str_join ":", ["a", "b", "c"]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment