summaryrefslogtreecommitdiff
path: root/ruby/luigi-template.rb
blob: d737fdc3fc207e714448101da7a7654835c2868e (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# require 'pp'

module Luigi
  #
  # library version
  #
  VERSION = '0.4.0'

  #
  # built-in filters
  #
  FILTERS = {
    # upper-case string
    uc: proc { |v, args, row, t|
      (v || '').to_s.upcase
    },

    # lower-case string
    lc: proc { |v, args, row, t|
      (v || '').to_s.downcase
    },

    # html-escape string
    h: proc { |v, args, row, t|
      (v || '').to_s.gsub(/&/, '&amp;').gsub(/</, '&lt;').gsub(/>/, '&gt;').gsub(/'/, '&apos').gsub(/"/, '&quot;')
    },

    # uri-escape string
    u: proc( { |v, args, row, t|
      require 'uri'
      URI.escape((v || '').to_s)
    },

    # json-encode value
    json: proc { |v, args, row, t|
      require 'json'
      v.to_json
    },

    # trim leading and trailing whitespace from string
    trim: proc { |v, args, row, t|
      (v || '').to_s.strip
    },

    # base64-encode string
    base64: proc { |v, args, row, t|
      [(v || '').to_s].pack('m')
    },

    # hash string
    hash: proc { |v, args, row, t|
      require 'openssl'
      OpenSSL::Digest.new(args[0] || 'md5').hexdigest((v || '').to_s)
    },
  }

  #
  # Template parser.
  #
  module Parser
    RES = {
      action: %r{
        # match opening brace
        %\{

        # match optional whitespace
        \s*

        # match key
        (?<key>[^\s\|\}]+)

        # match filter(s)
        (?<filters>(\s*\|(\s*[^\s\|\}]+)+)*)

        # match optional whitespace
        \s*

        # match closing brace
        \}

        # or match up all non-% chars or a single % char
        | (?<text>[^%]* | %)
      }mx,

      filter: %r{
        # match filter name
        (?<name>\S+)

        # match filter arguments (optional)
        (?<args>(\s*\S+)*)

        # optional trailing whitespace
        \s*
      }mx,

      delim_filters: %r{
        \s*\|\s*
      }mx,

      delim_args: %r{
        \s+
      },
    }

    #
    # Parse a (possibly empty) string into an array of actions.
    #
    def self.parse_template(str)
      str.scan(RES[:action]).map { |m|
        if m[0] && m[0].length > 0
          r = {
            type: :action,
            key: m[0].intern,
            filters: parse_filters(m[1]),
          }
        else
          # literal text
          r = { type: :text, text: m[2] }
        end

        # pp r

        # return result
        r
      }
    end

    #
    # Parse a (possibly empty) string into an array of filters.
    #
    def self.parse_filters(str)
      # strip leading and trailing whitespace
      str = (str || '').strip

      if str.length > 0
        str.strip.split(RES[:delim_filters]).inject([]) do |r, f|
          # strip whitespace
          f = f.strip

          if f.length > 0
            md = f.match(RES[:filter])
            raise "invalid filter: #{f}" unless md
            # pp md

            # get args
            args = md[:args].strip

            # add to result
            r << {
              name: md[:name].intern,
              args: args.length > 0 ? args.split(RES[:delim_args]) : [],
            }
          end

          # return result
          r
        end
      else
        # return empty filter set
        []
      end
    end
  end

  #
  # Template class.
  #
  class Template
    #
    # Create a new Template from the given string.
    #
    def initialize(str, filters = FILTERS)
      @str, @filters = str, filters
      @actions = Parser.parse_template(str)
    end

    #
    # Run template with given arguments
    #
    def run(args)
      @actions.map { |a|
        # pp a

        case a[:type]
        when :action
          # check key and get value
          val = if args.key?(a[:key])
            args[a[:key]]
          elsif args.key?(a[:key].to_s)
            args[a[:key].to_s]
          else
            # invalid key
            raise "unknown argument: #{a[:key]}"
          end

          # filter value
          a[:filters].inject(val) do |r, f|
            # check filter name
            raise "unknown filter: #{f[:name]}" unless @filters.key?(f[:name])

            # call filter, return result
            @filters[f[:name]].call(r, f[:args], args, self)
          end
        when :text
          # literal text
          a[:text]
        else
          # never reached
          raise "unknown action type: #{a[:type]}"
        end
      }.join
    end
  end

  #
  # Simple template cache.
  #
  class Cache
    #
    # Create a new template cache with the given templates
    #
    def initialize(strings, filters = FILTERS)
      @templates = Hash.new do |h, k|
        # always deal with symbols
        k = k.intern

        # make sure template exists
        raise "unknown template: #{k}" unless strings.key?(k)

        # create template
        h[k] = Template.new(strings[k], filters)
      end
    end

    #
    # Run specified template with given arguments.
    #
    def run(key, args)
      # run template with args and return result
      @templates[key].run(args)
    end
  end

  #
  # test module
  #
  module Test
    # test template
    TEMPLATE = '
      basic test: hello %{name}
      test filters: hello %{name | uc | base64 | hash sha1}
      test custom: hello %{name|custom}
      test custom_with_arg: %{name|custom_with_arg asdf}
    '

    CUSTOM_FILTERS = {
      custom: proc {
        'custom'
      },

      custom_with_arg: proc { |v, args|
        args.first || 'custom'
      },
    }

    # test template cache
    CACHE = {
      test: TEMPLATE
    }

    # test arguments
    ARGS = {
      name: 'paul',
    }

    def self.run
      # add custom filters
      Luigi::FILTERS.update(CUSTOM_FILTERS)

      # test individual template
      puts Template.new(TEMPLATE).run(ARGS)

      # test template cache
      puts Cache.new(CACHE).run(:test, ARGS)
    end
  end
end

Luigi::Test.run if __FILE__ == $0