class Tilt::YajlTemplate
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)
Public Instance Methods
decorate(json)
click to toggle source
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.
# File lib/tilt/yajl.rb 73 def decorate(json) 74 callback, variable = options[:callback], options[:variable] 75 if callback && variable 76 "var #{variable} = #{json}; #{callback}(#{variable});" 77 elsif variable 78 "var #{variable} = #{json};" 79 elsif callback 80 "#{callback}(#{json});" 81 else 82 json 83 end 84 end
evaluate(scope, locals, &block)
click to toggle source
Calls superclass method
Template#evaluate
# File lib/tilt/yajl.rb 49 def evaluate(scope, locals, &block) 50 decorate super(scope, locals, &block) 51 end
precompiled_postamble(locals)
click to toggle source
# File lib/tilt/yajl.rb 58 def precompiled_postamble(locals) 59 "Yajl::Encoder.new.encode(json)" 60 end
precompiled_preamble(locals)
click to toggle source
Calls superclass method
Template#precompiled_preamble
# File lib/tilt/yajl.rb 53 def precompiled_preamble(locals) 54 return super if locals.include? :json 55 "json = {}\n#{super}" 56 end
precompiled_template(locals)
click to toggle source
# File lib/tilt/yajl.rb 62 def precompiled_template(locals) 63 data.to_str 64 end
prepare()
click to toggle source
# File lib/tilt/yajl.rb 46 def prepare 47 end