simplest: instance_eval

This commit is contained in:
Marc Siegel 2011-12-06 14:46:46 -05:00
parent 2ebf7dc6f9
commit 2a6452b432
4 changed files with 105 additions and 2 deletions

View File

@ -5,5 +5,5 @@ require "yard/rake/yardoc_task"
YARD::Rake::YardocTask.new do |t|
OTHER_PATHS = %w(README.md LICENSE)
t.files = ['lib/**/*.rb', OTHER_PATHS]
t.options = ['--main README.md']
t.options = ['--main', 'README.md']
end

View File

@ -1,5 +1,23 @@
require "docile/version"
module Docile
# Your code goes here...
# Executes a block in the context of an object whose interface represents a DSL.
#
# Docile.dsl_eval([]) do
# push 1
# push 2
# pop
# push 3
# end
# #=> [1, 3]
#
# @param dsl [Object] an object whose methods represent a DSL
# @param block [Proc] a block to execute in the DSL context
# @return [Object] the given DSL object
def dsl_eval(dsl, &block)
block_context = eval("self", block.binding)
dsl.instance_eval(&block)
dsl
end
module_function :dsl_eval
end

75
spec/docile_spec.rb Normal file
View File

@ -0,0 +1,75 @@
require "spec_helper"
describe Docile do
context :dsl_eval do
class InnerDSL
def initialize; @b = 'b'; end
attr_accessor :b
end
class OuterDSL
def initialize; @a = 'a'; end
attr_accessor :a
def inner(&block)
Docile.dsl_eval(InnerDSL.new, &block)
end
end
def outer(&block)
Docile.dsl_eval(OuterDSL.new, &block)
end
it "should return the DSL object" do
Docile.dsl_eval([]) do
push 1
push 2
pop
push 3
end.should == [1, 3]
end
context "methods"
it "should find method of outer dsl in outer dsl scope" do
outer { a.should == 'a' }
end
it "should find method of inner dsl in inner dsl scope" do
outer { inner { b.should == 'b' } }
end
#it "should find method of outer dsl in inner dsl scope" do
# outer { inner { a.should == 'a' } }
#end
#
#it "should find method of block's context in outer dsl scope" do
# def c; 'c'; end
# outer { c.should == 'c' }
#end
#
#it "should find method of block's context in inner dsl scope" do
# def c; 'c'; end
# outer { inner { c.should == 'c' } }
#end
end
# it "should find local variable from block context in outer dsl scope" do
# foo = 'foo'
# outer { foo.should == 'foo' }
# end
#
#
#
# it "should find local variable from block definition in inner dsl scope" do
# bar = 'bar'
# outer { inner { bar.should == 'bar' } }
# end
#
# it "should find instance variable from block definition in inner dsl scope" do
# @iv1 = 'iv1'; outer { inner { @iv1.should == 'iv1' } }
# end
#end
end

10
spec/spec_helper.rb Normal file
View File

@ -0,0 +1,10 @@
require 'rubygems'
require 'rspec'
test_dir = File.dirname(__FILE__)
$LOAD_PATH.unshift test_dir unless $LOAD_PATH.include?(test_dir)
lib_dir = File.join(File.dirname(test_dir), 'lib')
$LOAD_PATH.unshift lib_dir unless $LOAD_PATH.include?(lib_dir)
require 'docile'