Class: Tilt::YajlTemplate
Overview
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)
Instance Attribute Summary
Attributes inherited from Template
#compiled_path, #data, #file, #line, #options
Instance Method Summary collapse
-
#decorate(json) ⇒ Object
Decorates the
json
input according to givenoptions
. - #evaluate(scope, locals, &block) ⇒ Object
- #precompiled_postamble(locals) ⇒ Object
- #precompiled_preamble(locals) ⇒ Object
- #precompiled_template(locals) ⇒ Object
- #prepare ⇒ Object
Methods inherited from Template
#basename, default_mime_type, default_mime_type=, #eval_file, #initialize, metadata, #metadata, #name, #render
Constructor Details
This class inherits a constructor from Tilt::Template
Instance Method Details
#decorate(json) ⇒ Object
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.
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/tilt/yajl.rb', line 73 def decorate(json) callback, variable = [:callback], [:variable] if callback && variable "var #{variable} = #{json}; #{callback}(#{variable});" elsif variable "var #{variable} = #{json};" elsif callback "#{callback}(#{json});" else json end end |
#evaluate(scope, locals, &block) ⇒ Object
49 50 51 |
# File 'lib/tilt/yajl.rb', line 49 def evaluate(scope, locals, &block) decorate super(scope, locals, &block) end |
#precompiled_postamble(locals) ⇒ Object
58 59 60 |
# File 'lib/tilt/yajl.rb', line 58 def precompiled_postamble(locals) "Yajl::Encoder.new.encode(json)" end |
#precompiled_preamble(locals) ⇒ Object
53 54 55 56 |
# File 'lib/tilt/yajl.rb', line 53 def precompiled_preamble(locals) return super if locals.include? :json "json = {}\n#{super}" end |
#precompiled_template(locals) ⇒ Object
62 63 64 |
# File 'lib/tilt/yajl.rb', line 62 def precompiled_template(locals) data.to_str end |
#prepare ⇒ Object
46 47 |
# File 'lib/tilt/yajl.rb', line 46 def prepare end |