{"id":13482563,"url":"https://github.com/ms-ati/docile","last_synced_at":"2025-06-30T15:02:16.295Z","repository":{"id":419833,"uuid":"2928790","full_name":"ms-ati/docile","owner":"ms-ati","description":"Docile keeps your Ruby DSLs tame and well-behaved","archived":false,"fork":false,"pushed_at":"2024-10-24T11:43:01.000Z","size":657,"stargazers_count":423,"open_issues_count":9,"forks_count":33,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-06-24T10:43:34.034Z","etag":null,"topics":["builder-pattern","dsl","immutability","ruby"],"latest_commit_sha":null,"homepage":"http://ms-ati.github.com/docile/","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ms-ati.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2011-12-06T23:03:34.000Z","updated_at":"2025-06-18T12:16:56.000Z","dependencies_parsed_at":"2024-06-17T16:30:50.725Z","dependency_job_id":"cddc4535-86c6-4f3e-8464-0eeba087de62","html_url":"https://github.com/ms-ati/docile","commit_stats":{"total_commits":335,"total_committers":24,"mean_commits":"13.958333333333334","dds":"0.33731343283582094","last_synced_commit":"f0c25f516b8fec16820c665345bfec5514a1ad09"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"purl":"pkg:github/ms-ati/docile","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ms-ati%2Fdocile","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ms-ati%2Fdocile/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ms-ati%2Fdocile/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ms-ati%2Fdocile/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ms-ati","download_url":"https://codeload.github.com/ms-ati/docile/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ms-ati%2Fdocile/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261859188,"owners_count":23220710,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["builder-pattern","dsl","immutability","ruby"],"created_at":"2024-07-31T17:01:03.279Z","updated_at":"2025-06-30T15:02:16.223Z","avatar_url":"https://github.com/ms-ati.png","language":"Ruby","readme":"# Docile\n\n[![Gem Version](https://img.shields.io/gem/v/docile.svg)](https://rubygems.org/gems/docile)\n[![Gem Downloads](https://img.shields.io/gem/dt/docile.svg)](https://rubygems.org/gems/docile)\n\n[![Join the chat at https://gitter.im/ms-ati/docile](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ms-ati/docile?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Yard Docs](http://img.shields.io/badge/yard-docs-blue.svg)](http://rubydoc.info/github/ms-ati/docile)\n\n[![Build Status](https://github.com/ms-ati/docile/actions/workflows/main.yml/badge.svg)](https://github.com/ms-ati/docile/actions/workflows/main.yml)\n[![Code Coverage](https://img.shields.io/codecov/c/github/ms-ati/docile.svg)](https://codecov.io/github/ms-ati/docile)\n[![Maintainability](https://api.codeclimate.com/v1/badges/79ca631bc123f7b83b34/maintainability)](https://codeclimate.com/github/ms-ati/docile/maintainability)\n\nRuby makes it possible to create very expressive **Domain Specific\nLanguages**, or **DSL**'s for short. However, it requires some deep knowledge and\nsomewhat hairy meta-programming to get the interface just right.\n\n\"Docile\" means *Ready to accept control or instruction; submissive* [[1]]\n\nInstead of each Ruby project reinventing this wheel, let's make our Ruby DSL\ncoding a bit more docile...\n\n[1]: http://www.google.com/search?q=docile+definition   \"Google\"\n\n## Usage\n\n### Basic: Ruby [Array](http://ruby-doc.org/core-3.0.0/Array.html) as DSL\n\nLet's say that we want to make a DSL for modifying Array objects.\nWouldn't it be great if we could just treat the methods of Array as a DSL?\n\n```ruby\nwith_array([]) do\n  push 1\n  push 2\n  pop\n  push 3\nend\n#=\u003e [1, 3]\n```\n\nNo problem, just define the method `with_array` like this:\n\n```ruby\ndef with_array(arr=[], \u0026block)\n  Docile.dsl_eval(arr, \u0026block)\nend\n```\n\nEasy!\n\n### Next step: Allow helper methods to call DSL methods\n\nWhat if, in our use of the methods of Array as a DSL, we want to extract\nhelper methods which in turn call DSL methods?\n\n```ruby\ndef pop_sum_and_push(n)\n  sum = 0\n  n.times { sum += pop }\n  push sum\nend\n\nDocile.dsl_eval([]) do\n  push 5\n  push 6\n  pop_sum_and_push(2)\nend\n#=\u003e [11]\n```\n\nWithout Docile, you may find this sort of code extraction to be more\nchallenging.\n\n### Wait! Can't I do that with just `instance_eval` or `instance_exec`?\n\nGood question!\n\nIn short: **No**. \n\nNot if you want the code in the block to be able to refer to anything\nthe block would normally have access to from the surrounding context.\n\nLet's be very specific. Docile internally uses `instance_exec` (see [execution.rb#26](lib/docile/execution.rb#L26)), adding a small layer to support referencing *local variables*, *instance variables*, and *methods* from the _block's context_ **or** the target _object's context_, interchangeably. This is \"**the hard part**\", where most folks making a DSL in Ruby throw up their hands.\n\nFor example:\n\n```ruby\nclass ContextOfBlock\n  def example_of_contexts\n    @block_instance_var = 1\n    block_local_var = 2\n\n    with_array do\n      push @block_instance_var\n      push block_local_var\n      pop\n      push block_sees_this_method \n    end\n  end\n  \n  def block_sees_this_method\n    3\n  end  \n\n  def with_array(\u0026block)\n    {\n      docile: Docile.dsl_eval([], \u0026block),\n      instance_eval: ([].instance_eval(\u0026block) rescue $!),\n      instance_exec: ([].instance_exec(\u0026block) rescue $!)\n    }  \n  end\nend\n\nContextOfBlock.new.example_of_contexts\n#=\u003e {\n      :docile=\u003e[1, 3],\n      :instance_eval=\u003e#\u003cNameError: undefined local variable or method `block_sees_this_method' for [nil]:Array\u003e,\n      :instance_exec=\u003e#\u003cNameError: undefined local variable or method `block_sees_this_method' for [nil]:Array\u003e\n    }\n```\n\nAs you can see, it won't be possible to call methods or access instance variables defined in the block's context using just the raw `instance_eval` or `instance_exec` methods. And in fact, Docile goes further, making it easy to maintain this support even in multi-layered DSLs.\n\n### Build a Pizza\n\nMutating (changing) an Array instance is fine, but what usually makes a good DSL is a [Builder Pattern][2].\n\nFor example, let's say you want a DSL to specify how you want to build a Pizza:\n\n```ruby\n@sauce_level = :extra\n\npizza do\n  cheese\n  pepperoni\n  sauce @sauce_level\nend\n#=\u003e #\u003cPizza:0x00001009dc398 @cheese=true, @pepperoni=true, @bacon=false, @sauce=:extra\u003e\n```\n\nAnd let's say we have a PizzaBuilder, which builds a Pizza like this:\n\n```ruby\nPizza = Struct.new(:cheese, :pepperoni, :bacon, :sauce)\n\nclass PizzaBuilder\n  def cheese(v=true); @cheese = v; self; end\n  def pepperoni(v=true); @pepperoni = v; self; end\n  def bacon(v=true); @bacon = v; self; end\n  def sauce(v=nil); @sauce = v; self; end\n  def build\n    Pizza.new(!!@cheese, !!@pepperoni, !!@bacon, @sauce)\n  end\nend\n\nPizzaBuilder.new.cheese.pepperoni.sauce(:extra).build\n#=\u003e #\u003cPizza:0x00001009dc398 @cheese=true, @pepperoni=true, @bacon=false, @sauce=:extra\u003e\n```\n\nThen implement your DSL like this:\n\n```ruby\ndef pizza(\u0026block)\n  Docile.dsl_eval(PizzaBuilder.new, \u0026block).build\nend\n```\n\nIt's just that easy!\n\n[2]: http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern  \"Builder Pattern\"\n\n### Multi-level and Recursive DSLs\n\nDocile is a very easy way to write a multi-level DSL in Ruby, even for\na [recursive data structure such as a tree][4]:\n\n```ruby\nPerson = Struct.new(:name, :mother, :father)\n\nperson {\n  name 'John Smith'\n  mother {\n    name 'Mary Smith'\n  }\n  father {\n    name 'Tom Smith'\n    mother {\n      name 'Jane Smith'\n    }\n  }\n}\n\n#=\u003e #\u003cstruct Person name=\"John Smith\",\n#                   mother=#\u003cstruct Person name=\"Mary Smith\", mother=nil, father=nil\u003e,\n#                   father=#\u003cstruct Person name=\"Tom Smith\",\n#                                          mother=#\u003cstruct Person name=\"Jane Smith\", mother=nil, father=nil\u003e,\n#                                          father=nil\u003e\u003e\n```\n\nSee the full [person tree example][4] for details.\n\n[4]: https://gist.github.com/ms-ati/2bb17bdf10a430faba98\n\n### Block parameters\n\nParameters can be passed to the DSL block.\n\nSupposing you want to make some sort of cheap [Sinatra][3] knockoff:\n\n```ruby\n@last_request = nil\nrespond '/path' do |request|\n  puts \"Request received: #{request}\"\n  @last_request = request\nend\n\ndef ride bike\n  # Play with your new bike\nend\n\nrespond '/new_bike' do |bike|\n  ride(bike)\nend\n```\n\nYou'd put together a dispatcher something like this:\n\n```ruby\nrequire 'singleton'\n\nclass DispatchScope\n  def a_method_you_can_call_from_inside_the_block\n    :useful_huh?\n  end\nend\n\nclass MessageDispatch\n  include Singleton\n\n  def initialize\n    @responders = {}\n  end\n\n  def add_responder path, \u0026block\n    @responders[path] = block\n  end\n\n  def dispatch path, request\n    Docile.dsl_eval(DispatchScope.new, request, \u0026@responders[path])\n  end\nend\n\ndef respond path, \u0026handler\n  MessageDispatch.instance.add_responder path, handler\nend\n\ndef send_request path, request\n  MessageDispatch.instance.dispatch path, request\nend\n```\n\n[3]: http://www.sinatrarb.com \"Sinatra\"\n\n### Functional-Style Immutable DSL Objects\n\nSometimes, you want to use an object as a DSL, but it doesn't quite fit the\n[imperative](http://en.wikipedia.org/wiki/Imperative_programming) pattern shown\nabove.\n\nInstead of methods like\n[Array#push](http://www.ruby-doc.org/core-3.0.0/Array.html#method-i-push), which\nmodifies the object at hand, it has methods like\n[String#reverse](http://www.ruby-doc.org/core-3.0.0/String.html#method-i-reverse),\nwhich returns a new object without touching the original. Perhaps it's even\n[frozen](http://www.ruby-doc.org/core-3.0.0/Object.html#method-i-freeze) in\norder to enforce [immutability](http://en.wikipedia.org/wiki/Immutable_object).\n\nWouldn't it be great if we could just treat these methods as a DSL as well?\n\n```ruby\ns = \"I'm immutable!\".freeze\n\nwith_immutable_string(s) do\n  reverse\n  upcase\nend\n#=\u003e \"!ELBATUMMI M'I\"\n\ns\n#=\u003e \"I'm immutable!\"\n```\n\nNo problem, just define the method `with_immutable_string` like this:\n\n```ruby\ndef with_immutable_string(str=\"\", \u0026block)\n  Docile.dsl_eval_immutable(str, \u0026block)\nend\n```\n\nAll set!\n\n### Accessing the block's return value\n\nSometimes you might want to access the return value of your provided block,\nas opposed to the DSL object itself. In these cases, use\n`dsl_eval_with_block_return`. It behaves exactly like `dsl_eval`, but returns\nthe output from executing the block, rather than the DSL object.\n\n```ruby\narr = []\nwith_array(arr) do\n  push \"a\"\n  push \"b\"\n  push \"c\"\n  length\nend\n#=\u003e 3\n\narr\n#=\u003e [\"a\", \"b\", \"c\"]\n```\n\n```ruby\ndef with_array(arr=[], \u0026block)\n  Docile.dsl_eval_with_block_return(arr, \u0026block)\nend\n```\n\n## Features\n\n  1.  Method lookup falls back from the DSL object to the block's context\n  2.  Local variable lookup falls back from the DSL object to the block's\n        context\n  3.  Instance variables are from the block's context only\n  4.  Nested DSL evaluation, correctly chaining method and variable handling\n        from the inner to the outer DSL scopes\n  5.  Alternatives for both imperative and functional styles of DSL objects\n\n## Installation\n\n``` bash\n$ gem install docile\n```\n\n## Links\n* [Source](https://github.com/ms-ati/docile)\n* [Documentation](http://rubydoc.info/gems/docile)\n* [Bug Tracker](https://github.com/ms-ati/docile/issues)\n\n## Status\n\nWorks on [all currently supported ruby versions](https://github.com/ms-ati/docile/blob/master/.github/workflows/main.yml),\nor so [Github Actions](https://github.com/ms-ati/docile/actions)\ntells us.\n\nUsed by some pretty cool gems to implement their DSLs, notably including\n[SimpleCov](https://github.com/colszowka/simplecov). Keep an eye out for new\ngems using Docile at the\n[Ruby Toolbox](https://www.ruby-toolbox.com/projects/docile).\n\n## Release Policy\n\nDocile releases follow\n[Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html).\n\n## Note on Patches/Pull Requests\n\n  * Fork the project.\n  * Setup your development environment with:\n      `gem install bundler; bundle install`\n  * Make your feature addition or bug fix.\n  * Add tests for it. This is important so I don't break it in a future version\n      unintentionally.\n  * Commit, do not mess with rakefile, version, or history.\n      (if you want to have your own version, that is fine but bump version in a\n      commit by itself I can ignore when I pull)\n  * Send me a pull request. Bonus points for topic branches.\n\n## Releasing\n\nTo make a new release of `Docile` to\n[RubyGems](https://rubygems.org/gems/docile), first install the release\ndependencies (e.g. `rake`) as follows:\n\n```shell\nbundle config set --local with 'release'\nbundle install\n```\n\nThen carry out these steps:\n\n1. Update `HISTORY.md`:\n    - Add an entry for the upcoming version _x.y.z_\n    - Move content from _Unreleased_ to the upcoming version _x.y.z_\n    - Commit with title `Update HISTORY.md for x.y.z`\n\n2. Update `lib/docile/version.rb`\n    - Replace with upcoming version _x.y.z_\n    - Commit with title `Bump version to x.y.z`\n\n3. `bundle exec rake release`\n\n## Copyright \u0026 License\n\nCopyright (c) 2012-2024 Marc Siegel.\n\nLicensed under the [MIT License](http://choosealicense.com/licenses/mit/),\nsee [LICENSE](LICENSE) for details.\n","funding_links":[],"categories":["Abstraction","Ruby","Core Extensions"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fms-ati%2Fdocile","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fms-ati%2Fdocile","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fms-ati%2Fdocile/lists"}