aboutsummaryrefslogtreecommitdiff
path: root/src/guff/template.cr
blob: 01a4c86e538e57f2b6dbf1df085c9d230de59776 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
module Guff
  class Template
    getter :string

    def initialize(@string : String)
      @tokens = scan(@string)
      @has_keys = @tokens.select { |t| t.type == :key }.size > 0
    end

    def run(args = nil : Hash(String, String)?) : String
      if @has_keys
        # check template args
        if args || args.size == 0
          raise "missing template args: %s" % [@tokens.select { |t| 
            t.type == :key
          }.join(", ")]
        end

        # build result
        String.builder do |r|
          @tokens.each do |t|
            r << t.get(args)
          end
        end
      else
        # no keys, return literal string
        @string
      end
    end

    SCAN_RE = %r{
      # match key
      (?:%\{(?<key>[^\}]+)\})

      |

      # match literal value
      (?<val>[^%]+)

      |

      # match literal percent
      (?<pct>%)
    }mx

    private def scan(s : String)
      r = [] of TemplateToken

      s.scan(SCAN_RE) do |md|
        if md["key"]?
          r << TemplateToken.new(:key, md["key"].strip)
        elsif md["val"]?
          r << TemplateToken.new(:val, md["val"])
        elsif md["pct"]?
          r << TemplateToken.new(:val, "%")
        else
          # never reached
          raise "unknown match: #{md}"
        end
      end

      # return result
      r
    end
  end
end