Skip to content

Commit

Permalink
scan variables and fallback values from a string template
Browse files Browse the repository at this point in the history
  • Loading branch information
ottohenrique committed Jul 5, 2021
1 parent cdbd11e commit 2e52f96
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
6 changes: 3 additions & 3 deletions spec/lib/template_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
describe TemplateParser do
context 'parse simple variables' do
it 'returns a list with found variable' do
expect(TemplateParser.new("{{ variable }}").variables).to eq(['variable'])
expect(TemplateParser.new("{{ variable }}").variables).to eq([['variable', nil]])
end

it 'returns a list with all found variables' do
expect(TemplateParser.new("{{ variable }} abc xyz {{ another_variable }}").variables).to eq(['another_variable', 'variable'])
expect(TemplateParser.new("{{ variable }} abc xyz {{ another_variable }}").variables).to eq([['variable', nil], ['another_variable', nil]])
end

it 'returns a list with variables and fallback values' do
expect(TemplateParser.new("{{ variable }} abc xyz {{ another_variable | fallback: 'xpto' }}").variables).to eq([['another_variable', 'xpto'], ['variable']])
expect(TemplateParser.new("{{ variable }} abc xyz {{ another_variable | fallback: 'xpto' }}").variables).to eq([['variable', nil], ['another_variable', 'xpto']])
end
end
end
11 changes: 9 additions & 2 deletions src/lib/template_parser.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class TemplateParser
VARIABLES = /{{\s?([\w]*)\s?(\|\s?fallback:\s?'[\w ]*'\s?)?}}/
COMPONENTS = /{{\s[a-zA-Z0-9_ ]\s|\sfallback:\s'.?'\s*}}/
FALLBACK = /\|\s?fallback:\s?'([a-z0-9_]+)'\s?/

attr_accessor :variables

Expand All @@ -12,7 +12,14 @@ def initialize(template)
private

def parse_variables
@variables ||= @template.scan(VARIABLES).map { |var, _| var.strip }.sort
@variables ||= @template.scan(VARIABLES).map do |variable, fallback|
if fallback.nil?
[variable, nil]
else
fallback_value = fallback.match(FALLBACK).captures.first
[variable, fallback_value]
end
end
end

end

0 comments on commit 2e52f96

Please sign in to comment.