Permalink
Browse files

eval via Subaltern::Context or via Subaltern

  • Loading branch information...
1 parent 875eae4 commit 54cf75fed6d2d2075814a8aeaceb83a0d6308bdd @jmettraux committed Oct 31, 2011
Showing with 61 additions and 8 deletions.
  1. +12 −0 README.md
  2. +1 −5 lib/subaltern.rb
  3. +25 −3 lib/subaltern/context.rb
  4. +23 −0 spec/context_spec.rb
View
12 README.md
@@ -4,6 +4,18 @@
Subaltern is a Ruby self-interpreter. It's sub-functional, it's a subaltern.
+## usage
+
+ require 'subaltern'
+
+ Subaltern.eval('1 + 1')
+ # => 2
+
+ c = Subaltern::Context.new('a' => 7)
+ c.eval('a + 2')
+ # => 9
+
+
## issues
https://github.com/jmettraux/subaltern/issues
View
6 lib/subaltern.rb
@@ -32,11 +32,7 @@ module Subaltern
def self.eval(source, vars={})
- begin
- eval_tree(Context.new(nil, vars), RubyParser.new.parse(source).to_a)
- rescue Return => r
- r.value
- end
+ Context.new(nil, vars).eval(source)
end
end
View
28 lib/subaltern/context.rb
@@ -30,10 +30,21 @@ class Context
attr_reader :parent
- def initialize(parent, vars)
+ # Create a new context
+ #
+ # c = Subaltern.new
+ # # or
+ # c = Subaltern.new('var0' => 'value0', 'var1' => [ 1, 2, 3 ])
+ #
+ def initialize(parent={}, vars=nil)
- @parent = parent
- @variables = vars
+ if vars.nil?
+ @parent = nil
+ @variables = parent
+ else
+ @parent = parent
+ @variables = vars
+ end
end
def [](key)
@@ -58,6 +69,17 @@ def has_key?(key)
@variables.has_key?(key)
end
+ # Eval a piece of Ruby code within this context.
+ #
+ def eval(source)
+
+ begin
+ Subaltern.eval_tree(self, RubyParser.new.parse(source).to_a)
+ rescue Return => r
+ r.value
+ end
+ end
+
protected
def set(key, value)
View
23 spec/context_spec.rb
@@ -0,0 +1,23 @@
+
+require 'spec_helper'
+
+
+describe Subaltern do
+
+ describe Subaltern::Context do
+
+ describe '.new' do
+
+ it 'is OK not to pass initial variables' do
+
+ Subaltern::Context.new.eval('1 + 1').should == 2
+ end
+
+ it 'is OK to pass initial variables' do
+
+ Subaltern::Context.new('a' => 7).eval('a + 1').should == 8
+ end
+ end
+ end
+end
+

0 comments on commit 54cf75f

Please sign in to comment.