Method: BBLib.pattern_render
- Defined in:
- lib/bblib/core/util/string.rb
.pattern_render(text, context = {}) ⇒ Object
Pattern render takes (by default) a mustache style template and then uses a context (either a Hash or Object) to then interpolate in placeholders. The default pattern looks for {method_name} within the string but can be customized to a different pattern by setting the pattern named argument.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/bblib/core/util/string.rb', line 102 def self.pattern_render(text, context = {}) raise ArgumentError, "Expected text argument to be a String, got a #{text.class}" unless text.is_a?(String) # TODO Make patterns customizable pattern = /\{{2}.*?\}{2}/ field_pattern = /(?<=^\{{2}).*(?=\}{2})/ txt = text.dup txt.scan(pattern).each do |match| field = match.scan(field_pattern).first next unless field value = case context when Hash context.hpath(field).first else context.send(field) if context.respond_to?(field) end.to_s txt.sub!(match, value) end txt end |