maetl / calyx

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

Provide an API/DSL for registering string mappings and transforms rather than monkeypatching #15

Closed maetl closed 8 years ago

maetl commented 8 years ago

This is something I’ve gone back and forward on.

I dislike monkeypatching in general, but it is really convenient to leverage the builtin Ruby String API—it’s well documented, requires next to no explanation of what methods are available, and doesn’t require learning a new API surface area.

However, one area where this falls down is in large and complex grammars where small mapping functions are really useful. Having to monkeypatch the global String class outside the grammar context kind of dilutes the focus and breaks any notion of encapsulation.

I assumed at the beginning this would be okay, as I never imagined Calyx being used anywhere beyond single purpose command line scripts. However, several people have pointed out to me that the library would also be useful in chatbots or web apps where slapping a bunch of stuff on the global String isn’t really an appropriate thing for a simple text generator to do.

As reference points, various imperative web template languages (Twig in PHP, Jinja in Python, Liquid in Ruby) require string transform filters to be explicitly bound to the runtime (although they do provide a bunch of helpful default filters). Whereas Tracery maps directly to the JavaScript builtin string functions (very similar to how Calyx currently works). Those are the two ends of the spectrum here.

tra38 commented 8 years ago

I do like leveraging the Ruby String API, but I can also understand why it might not be appropriate if you plan on a larger project.

Could it be possible to create a "CalyxString" class that simply inherits from the String class? Then you can just monkeypatch the CalyxString class, without worrying about impacting the main class.

maetl commented 8 years ago

Support for filter, transform and registration of modifier modules was added in 0.10.