Browse files

introduced NS object to represent a clojure namespace. Let's see where

this goes.
  • Loading branch information...
1 parent 1755459 commit 03bd4d2fdbfb7ed0534f87055f716e0710c510b5 @daveray committed Oct 16, 2011
Showing with 36 additions and 11 deletions.
  1. +29 −11 lib/familiar.rb
  2. +7 −0 test/test_familiar.rb
View
40 lib/familiar.rb
@@ -12,15 +12,33 @@
require "clojure-1.3.0.jar"
module Familiar
- # TODO why do I have this again?
- module Vars
- def self.[] (ns, var)
- m = Java::clojure.lang.RT.var(ns, var.to_s.gsub("_", "-"))
+ # Represents a Clojure namespace.
+ class NS
+ def initialize(ns)
+ @ns = ns
+ end
+
+ # Require this namespace so functions and vars are accessible.
+ # TODO should this be automatic?
+ def require
+ Familiar["clojure.core", :require].invoke(Familiar.symbol(@ns))
+ end
+
+ # Lookup a var in this namespace
+ def [] (var)
+ m = Java::clojure.lang.RT.var(@ns, var.to_s.gsub("_", "-"))
m.is_bound? ? m : nil
end
- def self.method_missing(meth, *args, &block)
- self["clojure.core", meth] or super
+ # All methods calls map to calling the same var in this namespace as
+ # a function. Underscores are automatically converted to hyphens.
+ def method_missing(meth, *args, &block)
+ m = self[meth]
+ if m
+ m.invoke(*args)
+ else
+ super
+ end
end
end
@@ -52,11 +70,12 @@ def self.[] (ns, var = nil)
var = ns
ns = "clojure.core"
end
- Familiar::Vars[ns, var]
+
+ # TODO cache namespaces?
+ Familiar::NS.new(ns)[var]
end
def self.method_missing(meth, *args, &block)
- #puts "Missing #{meth}"
m = self[meth]
if m
m.invoke(*args)
@@ -66,9 +85,7 @@ def self.method_missing(meth, *args, &block)
end
# Make inspect and to_s look right in irb
- [
- #Java::ClojureLang::LazySeq,
- Java::ClojureLang::PersistentVector,
+ [Java::ClojureLang::PersistentVector,
Java::ClojureLang::PersistentList,
Java::ClojureLang::PersistentArrayMap,
Java::ClojureLang::PersistentHashMap,
@@ -92,6 +109,7 @@ def inspect
end
end
+ # LazySeq gets special treatment to avoid killing IRB with infinite seqs.
[ Java::ClojureLang::LazySeq ].each do |x|
x.class_eval do
def inspect!
View
7 test/test_familiar.rb
@@ -13,6 +13,13 @@
class FamiliarTest < Test::Unit::TestCase
+ def test_can_require_a_namespace
+ f = Familiar
+ s = Familiar::NS.new("clojure.set")
+ assert s.require.nil?
+ assert_equal f.hash_set(1, 2, 3), s.union(f.hash_set(1, 2), f.hash_set(3, 2))
+ end
+
def test_to_s_looks_right
assert_equal '(1 2 3 4 5)', Familiar.list(1, 2, 3, 4, 5).to_s
assert_equal '[1 2 3 4 5]', Familiar.vector(1, 2, 3, 4, 5).to_s

0 comments on commit 03bd4d2

Please sign in to comment.