File: yajl.rb

package info (click to toggle)
ruby-tilt 2.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 632 kB
  • sloc: ruby: 4,975; makefile: 7
file content (91 lines) | stat: -rw-r--r-- 2,349 bytes parent folder | download
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
# frozen_string_literal: true

# = Yajl
#
# Yajl Template implementation
#
# Yajl is a fast JSON parsing and encoding library for Ruby
#
# The template source is evaluated as a Ruby string,
# and the result is converted #to_json.
#
# === Example
#
#    # This is a template example.
#    # The template can contain any Ruby statement.
#    tpl <<-EOS
#      @counter = 0
#
#      # The json variable represents the buffer
#      # and holds the data to be serialized into json.
#      # It defaults to an empty hash, but you can override it at any time.
#      json = {
#        :"user#{@counter += 1}" => { :name => "Joshua Peek", :id => @counter },
#        :"user#{@counter += 1}" => { :name => "Ryan Tomayko", :id => @counter },
#        :"user#{@counter += 1}" => { :name => "Simone Carletti", :id => @counter },
#      }
#
#      # Since the json variable is a Hash,
#      # you can use conditional statements or any other Ruby statement
#      # to populate it.
#      json[:"user#{@counter += 1}"] = { :name => "Unknown" } if 1 == 2
#
#      # The last line doesn't affect the returned value.
#      nil
#    EOS
#
#    template = Tilt::YajlTemplate.new { tpl }
#    template.render(self)
#
# === See also
#
# * https://github.com/brianmario/yajl-ruby
#
# === Related module
#
# * Tilt::YajlTemplate

require_relative 'template'
require 'yajl'

module Tilt
  class YajlTemplate < Template
    self.default_mime_type = 'application/json'

    def evaluate(scope, locals, &block)
      decorate(super)
    end

    def precompiled_preamble(locals)
      return super if locals.include? :json
      "json = {}\n#{super}"
    end

    def precompiled_postamble(locals)
      "Yajl::Encoder.new.encode(json)"
    end

    def precompiled_template(locals)
      @data.to_str
    end

    # Decorates the +json+ input according to given +options+.
    #
    # json    - The json String to decorate.
    # options - The option Hash to customize the behavior.
    #
    # Returns the decorated String.
    def decorate(json)
      callback, variable = @options[:callback], @options[:variable]
      if callback && variable
        "var #{variable} = #{json}; #{callback}(#{variable});"
      elsif variable
        "var #{variable} = #{json};"
      elsif callback
        "#{callback}(#{json});"
      else
        json
      end
    end
  end
end