maetl / calyx

A Ruby library for generating text with recursive template grammars.
MIT License
62 stars 5 forks source link

Support for template context map passed to `generate` #3

Closed maetl closed 8 years ago

maetl commented 8 years ago

Generators should be able to accept data passed in from other sources as a format for substitution.

Can already do this manually, by referencing variables or literals in scope during the definition process:

rule :villain, character.to_s
rule :protagonist, ['Vladimir', 'Estragon'].sample

This is often really useful, but having to pass in the data as part of the rule definition leads to messy grammars that are more difficult to reuse.

A possible solution is to support a template context map, passed to generate, similar to how Tilt and many other template engines work.

context = {
  protagonist: character.to_s
}

grammar = Grammar.new
grammar.generate(context)
maetl commented 8 years ago

Closed by 29378a85ee6a6fd0ffd2ea9f188b40b96cef4dad and released in 0.7.0.

I initially imagined it as a simple way to substitute variables into template expressions, but once I had implemented this, I realised that it was weird and lopsided to limit the passed-in values to only be Terminal substitutions. Now it’s implemented with the full rule parser, so entire grammars can be passed in.

As a consequence, it feels like this feature is playing a bit fast and loose with encapsulation of the core rule set, and raises a few questions about how to handle overwriting rules/combining and merging rules from different sources. These API design questions should be answered in the 0.7.* series I guess.