senny / sablon

Ruby Document Template Processor based on docx templates and Mail Merge fields.
MIT License
446 stars 128 forks source link

Implement merge field handler registration #99

Closed stadelmanma closed 6 years ago

stadelmanma commented 6 years ago

Creates an internal API that can be used to augment the current set of expressions that sablon supports. New field handlers can be added as well as existing ones removed or replaced. Additionally, a "default" handler exists that, if defined, is called when no other handler handles? the field.

The internal API is simple and consists of three class methods on Sablon::Processor::Document - .register_field_handler(name, handler), .replace_field_handler(name, handler) and .remove_field_handler(name). The do exactly what you would expect with the only caveat being you can't overwrite an existing handler using the register_field_handler method, use replace_field_handler instead.

The handler argument is an object that responds to two methods handles?(field) and build_statement(constructor, field, options = {}). If the return value of handles? is "truthy" (i.e. not false or nil) then the OperationConstruction instance (the constructor argument) will call the build_statement method and expect either nil or a Statement instance to be returned (or something that acts like one). The current field handlers are setup to only fire based on whether or not the field expression matches a given pattern however more complex conditions could be used if desired.

The goal of this is to allow the end user to easily implement features such as those requested in #72 and #73 without needing to formally fork the gem or use a fragile system of monkey patches. As such I am going to try and take those two cases and use them in test code to serve as examples for the future.

To Do:

closes #72 closes #73