Class Tilt::YajlTemplate
In: lib/tilt/yajl.rb
Parent: Template

Yajl Template implementation

Yajl is a fast JSON parsing and encoding library for Ruby See github.com/brianmario/yajl-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)

Methods

Public Class methods

[Source]

    # File lib/tilt/yajl.rb, line 45
45:     def self.engine_initialized?
46:       defined? ::Yajl
47:     end

Public Instance methods

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.

[Source]

    # File lib/tilt/yajl.rb, line 80
80:     def decorate(json)
81:       callback, variable = options[:callback], options[:variable]
82:       if callback && variable
83:         "var #{variable} = #{json}; #{callback}(#{variable});"
84:       elsif variable
85:         "var #{variable} = #{json};"
86:       elsif callback
87:         "#{callback}(#{json});"
88:       else
89:         json
90:       end
91:     end

[Source]

    # File lib/tilt/yajl.rb, line 56
56:     def evaluate(scope, locals, &block)
57:       decorate super(scope, locals, &block)
58:     end

[Source]

    # File lib/tilt/yajl.rb, line 49
49:     def initialize_engine
50:       require_template_library 'yajl'
51:     end

[Source]

    # File lib/tilt/yajl.rb, line 65
65:     def precompiled_postamble(locals)
66:       "Yajl::Encoder.new.encode(json)"
67:     end

[Source]

    # File lib/tilt/yajl.rb, line 60
60:     def precompiled_preamble(locals)
61:       return super if locals.include? :json
62:       "json = {}\n#{super}"
63:     end

[Source]

    # File lib/tilt/yajl.rb, line 69
69:     def precompiled_template(locals)
70:       data.to_str
71:     end

[Source]

    # File lib/tilt/yajl.rb, line 53
53:     def prepare
54:     end

[Validate]