docile-1.1.1/0000755000175000017500000000000012256134460010522 5ustar chchdocile-1.1.1/.travis.yml0000644000175000017500000000023012256134460012626 0ustar chchlanguage: ruby bundler_args: --without development rvm: - 2.0.0 - 1.9.3 - 1.9.2 - 1.8.7 - ree - jruby-18mode - jruby-19mode - rbx-2.2.0 docile-1.1.1/lib/0000755000175000017500000000000012256134460011270 5ustar chchdocile-1.1.1/lib/docile/0000755000175000017500000000000012256134460012527 5ustar chchdocile-1.1.1/lib/docile/execution.rb0000644000175000017500000000277312256134460015070 0ustar chchmodule Docile # @api private # # A namespace for functions relating to the execution of a block against a # proxy object. module Execution # Execute a block in the context of an object whose methods represent the # commands in a DSL, using a specific proxy class. # # @param dsl [Object] context object whose methods make up the # (initial) DSL # @param proxy_type [FallbackContextProxy, ChainingFallbackContextProxy] # which class to instantiate as proxy context # @param args [Array] arguments to be passed to the block # @param block [Proc] the block of DSL commands to be executed # @return [Object] the return value of the block def exec_in_proxy_context(dsl, proxy_type, *args, &block) block_context = eval('self', block.binding) proxy_context = proxy_type.new(dsl, proxy_type.new(dsl, block_context)) begin block_context.instance_variables.each do |ivar| value_from_block = block_context.instance_variable_get(ivar) proxy_context.instance_variable_set(ivar, value_from_block) end proxy_context.instance_exec(*args, &block) ensure block_context.instance_variables.each do |ivar| value_from_dsl_proxy = proxy_context.instance_variable_get(ivar) block_context.instance_variable_set(ivar, value_from_dsl_proxy) end end end module_function :exec_in_proxy_context end enddocile-1.1.1/lib/docile/chaining_fallback_context_proxy.rb0000644000175000017500000000120312256134460021454 0ustar chchrequire 'docile/fallback_context_proxy' module Docile # @api private # # Operates in the same manner as {FallbackContextProxy}, but replacing # the primary `receiver` object with the result of each proxied method. # # This is useful for implementing DSL evaluation for immutable context # objects. # # @see Docile.dsl_eval_immutable class ChainingFallbackContextProxy < FallbackContextProxy # Proxy methods as in {FallbackContextProxy#method_missing}, replacing # `receiver` with the returned value. def method_missing(method, *args, &block) @__receiver__ = super(method, *args, &block) end end enddocile-1.1.1/lib/docile/version.rb0000644000175000017500000000011612256134460014537 0ustar chchmodule Docile # The current version of this library VERSION = '1.1.1' end docile-1.1.1/lib/docile/fallback_context_proxy.rb0000644000175000017500000000467712256134460017636 0ustar chchrequire 'set' module Docile # @api private # # A proxy object with a primary receiver as well as a secondary # fallback receiver. # # Will attempt to forward all method calls first to the primary receiver, # and then to the fallback receiver if the primary does not handle that # method. # # This is useful for implementing DSL evaluation in the context of an object. # # @see Docile.dsl_eval class FallbackContextProxy # The set of methods which will **not** be proxied, but instead answered # by this object directly. NON_PROXIED_METHODS = Set[:__send__, :object_id, :__id__, :==, :equal?, :'!', :'!=', :instance_exec, :instance_variables, :instance_variable_get, :instance_variable_set, :remove_instance_variable] # The set of instance variables which are local to this object and hidden. # All other instance variables will be copied in and out of this object # from the scope in which this proxy was created. NON_PROXIED_INSTANCE_VARIABLES = Set[:@__receiver__, :@__fallback__] # Undefine all instance methods except those in {NON_PROXIED_METHODS} instance_methods.each do |method| undef_method(method) unless NON_PROXIED_METHODS.include?(method.to_sym) end # @param [Object] receiver the primary proxy target to which all methods # initially will be forwarded # @param [Object] fallback the fallback proxy target to which any methods # not handled by `receiver` will be forwarded def initialize(receiver, fallback) @__receiver__ = receiver @__fallback__ = fallback end # @return [Array] Instance variable names, excluding # {NON_PROXIED_INSTANCE_VARIABLES} # # @note on Ruby 1.8.x, the instance variable names are actually of # type `String`. def instance_variables # Ruby 1.8.x returns string names, convert to symbols for compatibility super.select { |v| !NON_PROXIED_INSTANCE_VARIABLES.include?(v.to_sym) } end # Proxy all methods, excluding {NON_PROXIED_METHODS}, first to `receiver` # and then to `fallback` if not found. def method_missing(method, *args, &block) @__receiver__.__send__(method.to_sym, *args, &block) rescue ::NoMethodError => e @__fallback__.__send__(method.to_sym, *args, &block) end end end docile-1.1.1/lib/docile.rb0000644000175000017500000000545412256134460013064 0ustar chchrequire 'docile/version' require 'docile/execution' require 'docile/fallback_context_proxy' require 'docile/chaining_fallback_context_proxy' # Docile keeps your Ruby DSLs tame and well-behaved. module Docile extend Execution # Execute a block in the context of an object whose methods represent the # commands in a DSL. # # @note Use with an *imperative* DSL (commands modify the context object) # # Use this method to execute an *imperative* DSL, which means that: # # 1. Each command mutates the state of the DSL context object # 2. The return value of each command is ignored # 3. The final return value is the original context object # # @example Use a String as a DSL # Docile.dsl_eval("Hello, world!") do # reverse! # upcase! # end # #=> "!DLROW ,OLLEH" # # @example Use an Array as a DSL # Docile.dsl_eval([]) do # push 1 # push 2 # pop # push 3 # end # #=> [1, 3] # # @param dsl [Object] context object whose methods make up the DSL # @param args [Array] arguments to be passed to the block # @param block [Proc] the block of DSL commands to be executed against the # `dsl` context object # @return [Object] the `dsl` context object after executing the block def dsl_eval(dsl, *args, &block) exec_in_proxy_context(dsl, FallbackContextProxy, *args, &block) dsl end module_function :dsl_eval # Execute a block in the context of an immutable object whose methods, # and the methods of their return values, represent the commands in a DSL. # # @note Use with a *functional* DSL (commands return successor # context objects) # # Use this method to execute a *functional* DSL, which means that: # # 1. The original DSL context object is never mutated # 2. Each command returns the next DSL context object # 3. The final return value is the value returned by the last command # # @example Use a frozen String as a DSL # Docile.dsl_eval_immutable("I'm immutable!".freeze) do # reverse # upcase # end # #=> "!ELBATUMMI M'I" # # @example Use a Float as a DSL # Docile.dsl_eval_immutable(84.5) do # fdiv(2) # floor # end # #=> 42 # # @param dsl [Object] immutable context object whose methods make up the # initial DSL # @param args [Array] arguments to be passed to the block # @param block [Proc] the block of DSL commands to be executed against the # `dsl` context object and successor return values # @return [Object] the return value of the final command in the block def dsl_eval_immutable(dsl, *args, &block) exec_in_proxy_context(dsl, ChainingFallbackContextProxy, *args, &block) end module_function :dsl_eval_immutable end docile-1.1.1/.rspec0000644000175000017500000000003612256134460011636 0ustar chch--color --format documentationdocile-1.1.1/.coveralls.yml0000644000175000017500000000003112256134460013307 0ustar chchservice_name: travis-ci docile-1.1.1/LICENSE0000644000175000017500000000204312256134460011526 0ustar chchCopyright (c) 2012-2013 Marc Siegel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.docile-1.1.1/.ruby-version0000644000175000017500000000001312256134460013161 0ustar chchruby-2.0.0 docile-1.1.1/Rakefile0000644000175000017500000000125412256134460012171 0ustar chchrequire 'rake/clean' require 'bundler/gem_tasks' require 'rspec/core/rake_task' # Default task for `rake` is to run rspec task :default => [:spec] # Use default rspec rake task RSpec::Core::RakeTask.new # Configure `rake clobber` to delete all generated files CLOBBER.include('pkg', 'doc', 'coverage') # Only configure yard doc generation when *not* on Travis if ENV['CI'] != 'true' require "github/markup" require "redcarpet" require "yard" require "yard/rake/yardoc_task" YARD::Rake::YardocTask.new do |t| OTHER_PATHS = %w() t.files = ['lib/**/*.rb', OTHER_PATHS] t.options = %w(--markup-provider=redcarpet --markup=markdown --main=README.md) end end docile-1.1.1/README.md0000644000175000017500000001361612256134460012010 0ustar chch# Docile [![Gem Version](https://badge.fury.io/rb/docile.png)](http://badge.fury.io/rb/docile) [![Build Status](https://travis-ci.org/ms-ati/docile.png)](https://travis-ci.org/ms-ati/docile) [![Dependency Status](https://gemnasium.com/ms-ati/docile.png)](https://gemnasium.com/ms-ati/docile) [![Code Climate](https://codeclimate.com/github/ms-ati/docile.png)](https://codeclimate.com/github/ms-ati/docile) [![Coverage Status](https://coveralls.io/repos/ms-ati/docile/badge.png)](https://coveralls.io/r/ms-ati/docile) Ruby makes it possible to create very expressive **Domain Specific Languages**, or **DSL**'s for short. However, it requires some deep knowledge and somewhat hairy meta-programming to get the interface just right. "Docile" means *Ready to accept control or instruction; submissive* [[1]] Instead of each Ruby project reinventing this wheel, let's make our Ruby DSL coding a bit more docile... [1]: http://www.google.com/search?q=docile+definition "Google" ## Usage ### Basic Let's say that we want to make a DSL for modifying Array objects. Wouldn't it be great if we could just treat the methods of Array as a DSL? ```ruby with_array([]) do push 1 push 2 pop push 3 end #=> [1, 3] ``` No problem, just define the method `with_array` like this: ```ruby def with_array(arr=[], &block) Docile.dsl_eval(arr, &block) end ``` Easy! ### Advanced Mutating (changing) an Array instance is fine, but what usually makes a good DSL is a [Builder Pattern][2]. For example, let's say you want a DSL to specify how you want to build a Pizza: ```ruby @sauce_level = :extra pizza do cheese pepperoni sauce @sauce_level end #=> # ``` And let's say we have a PizzaBuilder, which builds a Pizza like this: ```ruby Pizza = Struct.new(:cheese, :pepperoni, :bacon, :sauce) class PizzaBuilder def cheese(v=true); @cheese = v; self; end def pepperoni(v=true); @pepperoni = v; self; end def bacon(v=true); @bacon = v; self; end def sauce(v=nil); @sauce = v; self; end def build Pizza.new(!!@cheese, !!@pepperoni, !!@bacon, @sauce) end end PizzaBuilder.new.cheese.pepperoni.sauce(:extra).build #=> # ``` Then implement your DSL like this: ``` ruby def pizza(&block) Docile.dsl_eval(PizzaBuilder.new, &block).build end ``` It's just that easy! [2]: http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern "Builder Pattern" ### Block parameters Parameters can be passed to the DSL block. Supposing you want to make some sort of cheap [Sinatra][3] knockoff: ```ruby @last_request = nil respond '/path' do |request| puts "Request received: #{request}" @last_request = request end def ride bike # Play with your new bike end respond '/new_bike' do |bike| ride(bike) end ``` You'd put together a dispatcher something like this: ```ruby require 'singleton' class DispatchScope def a_method_you_can_call_from_inside_the_block :useful_huh? end end class MessageDispatch include Singleton def initialize @responders = {} end def add_responder path, &block @responders[path] = block end def dispatch path, request Docile.dsl_eval(DispatchScope.new, request, &@responders[path]) end end def respond path, &handler MessageDispatch.instance.add_responder path, handler end def send_request path, request MessageDispatch.instance.dispatch path, request end ``` [3]: http://www.sinatrarb.com "Sinatra" ### Functional-Style DSL Objects Sometimes, you want to use an object as a DSL, but it doesn't quite fit the [imperative](http://en.wikipedia.org/wiki/Imperative_programming) pattern shown above. Instead of methods like [Array#push](http://www.ruby-doc.org/core-2.0/Array.html#method-i-push), which modifies the object at hand, it has methods like [String#reverse](http://www.ruby-doc.org/core-2.0/String.html#method-i-reverse), which returns a new object without touching the original. Perhaps it's even [frozen](http://www.ruby-doc.org/core-2.0/Object.html#method-i-freeze) in order to enforce [immutability](http://en.wikipedia.org/wiki/Immutable_object). Wouldn't it be great if we could just treat these methods as a DSL as well? ```ruby s = "I'm immutable!".freeze with_immutable_string(s) do reverse upcase end #=> "!ELBATUMMI M'I" s #=> "I'm immutable!" ``` No problem, just define the method `with_immutable_string` like this: ```ruby def with_immutable_string(str="", &block) Docile.dsl_eval_immutable(str, &block) end ``` All set! ## Features 1. Method lookup falls back from the DSL object to the block's context 2. Local variable lookup falls back from the DSL object to the block's context 3. Instance variables are from the block's context only 4. Nested DSL evaluation, correctly chaining method and variable handling from the inner to the outer DSL scopes 5. Alternatives for both imperative and functional styles of DSL objects ## Installation ``` bash $ gem install docile ``` ## Links * [Source](https://github.com/ms-ati/docile) * [Documentation](http://rubydoc.info/gems/docile) * [Bug Tracker](https://github.com/ms-ati/docile/issues) ## Status Works on [all ruby versions since 1.8.7](https://github.com/ms-ati/docile/blob/master/.travis.yml). ## Note on Patches/Pull Requests * Fork the project. * Setup your development environment with: `gem install bundler; bundle install` * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Bonus points for topic branches. ## Copyright Copyright (c) 2012-2013 Marc Siegel. See LICENSE for details. docile-1.1.1/HISTORY.md0000644000175000017500000000247712256134460012217 0ustar chch# HISTORY ## [v1.1.1 (Nov 26, 2013)](http://github.com/ms-ati/docile/compare/v1.1.0...v1.1.1) - documentation updates and corrections - fix Rubinius build in Travis CI ## [v1.1.0 (Jul 29, 2013)](http://github.com/ms-ati/docile/compare/v1.0.5...v1.1.0) - add functional-style DSL objects via `Docile#dsl_eval_immutable` ## [v1.0.5 (Jul 28, 2013)](http://github.com/ms-ati/docile/compare/v1.0.4...v1.0.5) - achieve 100% yard docs coverage - fix rendering of docs at http://rubydoc.info/gems/docile ## [v1.0.4 (Jul 25, 2013)](http://github.com/ms-ati/docile/compare/v1.0.3...v1.0.4) - simplify and clarify code - fix a minor bug where FallbackContextProxy#instance_variables would return symbols rather than strings on Ruby 1.8.x ## [v1.0.3 (Jul 6, 2013)](http://github.com/ms-ati/docile/compare/v1.0.2...v1.0.3) - instrument code coverage via SimpleCov and publish to Coveralls.io ## [v1.0.2 (Apr 1, 2013)](http://github.com/ms-ati/docile/compare/v1.0.1...v1.0.2) - allow passing parameters to DSL blocks (thanks @dslh!) ## [v1.0.1 (Nov 29, 2012)](http://github.com/ms-ati/docile/compare/v1.0.0...v1.0.1) - relaxed rspec and rake dependencies to allow newer versions - fixes to documentation ## [v1.0.0 (Oct 29, 2012)](http://github.com/ms-ati/docile/compare/1b225c8a27...v1.0.0) - Initial Feature Setdocile-1.1.1/docile.gemspec0000644000175000017500000000231512256134460013327 0ustar chch$:.push File.expand_path('../lib', __FILE__) require 'docile/version' Gem::Specification.new do |s| s.name = 'docile' s.version = Docile::VERSION s.authors = ['Marc Siegel'] s.email = %w(msiegel@usainnov.com) s.homepage = 'http://ms-ati.github.com/docile/' s.summary = 'Docile keeps your Ruby DSLs tame and well-behaved' s.description = 'Docile turns any Ruby object into a DSL. Especially useful with the Builder pattern.' s.license = 'MIT' s.rubyforge_project = 'docile' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = %w(lib) # Running rspec tests from rake s.add_development_dependency 'rake', '~> 0.9.2' s.add_development_dependency 'rspec', '~> 2.11.0' # Github flavored markdown in YARD documentation # http://blog.nikosd.com/2011/11/github-flavored-markdown-in-yard.html s.add_development_dependency 'yard' s.add_development_dependency 'redcarpet' s.add_development_dependency 'github-markup' # Coveralls test coverage tool s.add_development_dependency 'coveralls' end docile-1.1.1/.gitignore0000644000175000017500000000007212256134460012511 0ustar chch*.gem .bundle Gemfile.lock pkg .idea doc .yardoc coverage docile-1.1.1/checksums.yaml.gz0000444000175000017500000000041512256134460014010 0ustar chch Re1R@E"@:;{O X8<Kmyvr~}v+b! dV ·ea{ F]#Uv\l4/Wi)*%6HF>31Ju*k6Zڞ+{ళZ\XadDkk r w+`*ɕzRl%pP# )<6m6&}cϛK,uuր"ͫާ8?c|ddocile-1.1.1/metadata.yml0000644000175000017500000000677112256134460013040 0ustar chch--- !ruby/object:Gem::Specification name: docile version: !ruby/object:Gem::Version version: 1.1.1 platform: ruby authors: - Marc Siegel autorequire: bindir: bin cert_chain: [] date: 2013-11-26 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: 0.9.2 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: 0.9.2 - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: 2.11.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: 2.11.0 - !ruby/object:Gem::Dependency name: yard requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: redcarpet requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: github-markup requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: coveralls requirement: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' description: Docile turns any Ruby object into a DSL. Especially useful with the Builder pattern. email: - msiegel@usainnov.com executables: [] extensions: [] extra_rdoc_files: [] files: - .coveralls.yml - .gitignore - .rspec - .ruby-gemset - .ruby-version - .travis.yml - .yardopts - Gemfile - HISTORY.md - LICENSE - README.md - Rakefile - docile.gemspec - lib/docile.rb - lib/docile/chaining_fallback_context_proxy.rb - lib/docile/execution.rb - lib/docile/fallback_context_proxy.rb - lib/docile/version.rb - spec/docile_spec.rb - spec/spec_helper.rb homepage: http://ms-ati.github.com/docile/ licenses: - MIT metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: docile rubygems_version: 2.1.11 signing_key: specification_version: 4 summary: Docile keeps your Ruby DSLs tame and well-behaved test_files: - spec/docile_spec.rb - spec/spec_helper.rb has_rdoc: docile-1.1.1/.yardopts0000644000175000017500000000015512256134460012371 0ustar chch--title 'Docile Documentation' --no-private --main=README.md --markup-provider=redcarpet --markup=markdown docile-1.1.1/.ruby-gemset0000644000175000017500000000000712256134460012763 0ustar chchdocile docile-1.1.1/Gemfile0000644000175000017500000000075612256134460012025 0ustar chchsource 'https://rubygems.org' # Specify gem's dependencies in docile.gemspec gemspec # Explicitly require test gems for Travis CI, since we're excluding dev dependencies group :test do gem 'rake', '~> 0.9.2' gem 'rspec', '~> 2.11.0' gem 'mime-types', '~> 1.25.1' gem 'coveralls', :require => false platform :rbx do gem 'rubysl' # Since 2.2.0, Rubinius needs Ruby standard lib as gem gem 'rubinius-coverage' # Coverage tooling for SimpleCov on Rubinius end end docile-1.1.1/spec/0000755000175000017500000000000012256134460011454 5ustar chchdocile-1.1.1/spec/docile_spec.rb0000644000175000017500000002056212256134460014257 0ustar chchrequire 'spec_helper' describe Docile do describe '.dsl_eval' do context 'when DSL context object is an Array' do let(:array) { [] } let!(:result) { execute_dsl_against_array } def execute_dsl_against_array Docile.dsl_eval(array) do push 1 push 2 pop push 3 end end it 'executes the block against the DSL context object' do array.should == [1, 3] end it 'returns the DSL object after executing block against it' do result.should == array end it "doesn't proxy #__id__" do Docile.dsl_eval(array) { __id__.should_not == array.__id__ } end it "raises NoMethodError if the DSL object doesn't implement the method" do expect { Docile.dsl_eval(array) { no_such_method } }.to raise_error(NoMethodError) end end Pizza = Struct.new(:cheese, :pepperoni, :bacon, :sauce) class PizzaBuilder def cheese(v=true); @cheese = v; end def pepperoni(v=true); @pepperoni = v; end def bacon(v=true); @bacon = v; end def sauce(v=nil); @sauce = v; end def build Pizza.new(!!@cheese, !!@pepperoni, !!@bacon, @sauce) end end context 'when DSL context object is a Builder pattern' do let(:builder) { PizzaBuilder.new } let(:result) { execute_dsl_against_builder_and_call_build } def execute_dsl_against_builder_and_call_build @sauce = :extra Docile.dsl_eval(builder) do bacon cheese sauce @sauce end.build end it 'returns correctly built object' do result.should == Pizza.new(true, false, true, :extra) end end 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 def inner_with_params(param, &block) Docile.dsl_eval(InnerDSL.new, param, :foo, &block) end end def outer(&block) Docile.dsl_eval(OuterDSL.new, &block) end context 'when given parameters for the DSL block' do def parameterized(*args, &block) Docile.dsl_eval(OuterDSL.new, *args, &block) end it 'passes parameters to the block' do parameterized(1,2,3) do |x,y,z| x.should == 1 y.should == 2 z.should == 3 end end it 'finds parameters before methods' do parameterized(1) { |a| a.should == 1 } end it 'find outer dsl parameters in inner dsl scope' do parameterized(1,2,3) do |a,b,c| inner_with_params(c) do |d,e| a.should == 1 b.should == 2 c.should == 3 d.should == c e.should == :foo end end end end context 'when DSL blocks are nested' do context 'method lookup' do it 'finds method of outer dsl in outer dsl scope' do outer { a.should == 'a' } end it 'finds method of inner dsl in inner dsl scope' do outer { inner { b.should == 'b' } } end it 'finds method of outer dsl in inner dsl scope' do outer { inner { a.should == 'a' } } end it "finds method of block's context in outer dsl scope" do def c; 'c'; end outer { c.should == 'c' } end it "finds method of block's context in inner dsl scope" do def c; 'c'; end outer { inner { c.should == 'c' } } end it 'finds method of outer dsl in preference to block context' do def a; 'not a'; end outer { a.should == 'a' } outer { inner { a.should == 'a' } } end end context 'local variable lookup' do it 'finds local variable from block context in outer dsl scope' do foo = 'foo' outer { foo.should == 'foo' } end it 'finds local variable from block definition in inner dsl scope' do bar = 'bar' outer { inner { bar.should == 'bar' } } end end context 'instance variable lookup' do it 'finds instance variable from block definition in outer dsl scope' do @iv1 = 'iv1'; outer { @iv1.should == 'iv1' } end it "proxies instance variable assignments in block in outer dsl scope back into block's context" do @iv1 = 'foo'; outer { @iv1 = 'bar' }; @iv1.should == 'bar' end it 'finds instance variable from block definition in inner dsl scope' do @iv2 = 'iv2'; outer { inner { @iv2.should == 'iv2' } } end it "proxies instance variable assignments in block in inner dsl scope back into block's context" do @iv2 = 'foo'; outer { inner { @iv2 = 'bar' } }; @iv2.should == 'bar' end end end context 'when DSL context object is a Dispatch pattern' do class DispatchScope def params { :a => 1, :b => 2, :c => 3 } end end class MessageDispatch include Singleton def initialize @responders = {} end def add_responder path, &block @responders[path] = block end def dispatch path, request Docile.dsl_eval(DispatchScope.new, request, &@responders[path]) end end def respond(path, &block) MessageDispatch.instance.add_responder(path, &block) end def send_request(path, request) MessageDispatch.instance.dispatch(path, request) end it 'dispatches correctly' do @first = @second = nil respond '/path' do |request| @first = request end respond '/new_bike' do |bike| @second = "Got a new #{bike}" end def x(y) ; "Got a #{y}"; end respond '/third' do |third| x(third).should == 'Got a third thing' end fourth = nil respond '/params' do |arg| fourth = params[arg] end send_request '/path', 1 send_request '/new_bike', 'ten speed' send_request '/third', 'third thing' send_request '/params', :b @first.should == 1 @second.should == 'Got a new ten speed' fourth.should == 2 end end end describe '.dsl_eval_immutable' do context 'when DSL context object is a frozen String' do let(:original) { "I'm immutable!".freeze } let!(:result) { execute_non_mutating_dsl_against_string } def execute_non_mutating_dsl_against_string Docile.dsl_eval_immutable(original) do reverse upcase end end it "doesn't modify the original string" do original.should == "I'm immutable!" end it 'chains the commands in the block against the DSL context object' do result.should == "!ELBATUMMI M'I" end end context 'when DSL context object is a number' do let(:original) { 84.5 } let!(:result) { execute_non_mutating_dsl_against_number } def execute_non_mutating_dsl_against_number Docile.dsl_eval_immutable(original) do fdiv(2) floor end end it 'chains the commands in the block against the DSL context object' do result.should == 42 end end end end describe Docile::FallbackContextProxy do describe "#instance_variables" do subject { create_fcp_and_set_one_instance_variable.instance_variables } let(:expected_type_of_names) { type_of_ivar_names_on_this_ruby } let(:actual_type_of_names) { subject.first.class } let(:excluded) { Docile::FallbackContextProxy::NON_PROXIED_INSTANCE_VARIABLES } def create_fcp_and_set_one_instance_variable fcp = Docile::FallbackContextProxy.new(nil, nil) fcp.instance_variable_set(:@foo, 'foo') fcp end def type_of_ivar_names_on_this_ruby @a = 1 instance_variables.first.class end it 'returns proxied instance variables' do subject.map(&:to_sym).should include(:@foo) end it "doesn't return non-proxied instance variables" do subject.map(&:to_sym).should_not include(*excluded) end it 'preserves the type (String or Symbol) of names on this ruby version' do actual_type_of_names.should == expected_type_of_names end end end docile-1.1.1/spec/spec_helper.rb0000644000175000017500000000106012256134460014267 0ustar chchrequire 'rubygems' require 'rspec' require 'singleton' require 'simplecov' require 'coveralls' # Both local SimpleCov and publish to Coveralls.io SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.start do add_filter "/spec/" end 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'