Module: Twin::Template
- Defined in:
- lib/twin/template.rb
Constant Summary collapse
- PATTERN =
/\{\{([^}]+)\}\}/- FIELDS =
Fields in a grubber record that may contain {tokens}.
%w[Source Target Path Target-Path Exclude Cmd].freeze
Class Method Summary collapse
-
.render_file(path, vars, context:) ⇒ Object
Read a template file and substitute {tokens} in its content.
-
.substitute(value, vars, context:) ⇒ Object
Replace {token} in value using vars.
-
.substitute_record(r, vars, context:) ⇒ Object
Return a copy of grubber record r with FIELDS substituted.
Class Method Details
.render_file(path, vars, context:) ⇒ Object
Read a template file and substitute {tokens} in its content. Binary read preserves bytes exactly; raises on unknown token.
21 22 23 |
# File 'lib/twin/template.rb', line 21 def render_file(path, vars, context:) substitute(File.binread(path), vars, context: context) end |
.substitute(value, vars, context:) ⇒ Object
Replace {token} in value using vars. Raises on unknown token.
11 12 13 14 15 16 17 |
# File 'lib/twin/template.rb', line 11 def substitute(value, vars, context:) return value unless value.is_a?(String) value.gsub(PATTERN) do token = $1 vars.fetch(token) { raise "unknown template token {{#{token}}} in #{context}" } end end |
.substitute_record(r, vars, context:) ⇒ Object
Return a copy of grubber record r with FIELDS substituted.
26 27 28 29 30 31 32 33 34 |
# File 'lib/twin/template.rb', line 26 def substitute_record(r, vars, context:) return r if vars.empty? result = r.dup FIELDS.each do |field| next unless result.key?(field) && result[field].is_a?(String) result[field] = substitute(result[field], vars, context: context) end result end |