Mustache JSON Serialization

The mustache_json gem provides a simple way to encode Mustaches into JSON for cross-compatibility with other Mustache rendering libraries such as mustache.js (github.com/janl/mustache.js).

Installation

Mustache JSON is available as a gem on Gemcutter:

gem install mustache_json

Usage

It extends Mustache in a simple way such that all public instance methods declared in your Mustache will be automatically serialized into json when the #to_json method is called. Any context variables that have been set will be included as well. For example, take this Mustache:

require 'mustache_json'

class Person < Mustache
  def initialize(first_name, last_name)
    context[:first_name], context[:last_name] = first_name, last_name
  end

  def initials
    "#{context[:first_name][0..0]}.#{context[:last_name][0..0]}."
  end

  def listing
    "#{context[:last_name]}, #{context[:first_name]}"
  end
end

With mustache_json you are able to do this:

bob = Person.new('Bob', 'Bobson')
bob.to_json

Which will output:

{"last_name":"Bobson","initials":"B.B.","listing":"Bobson, Bob","first_name":"Bob"}

It’s a simple addition to Mustache but provides some powerful functionality toward views that can be rendered either server-side (in Ruby) or client-side (in Javascript).

Swappable JSON Backends

This library doesn’t depend on any specific JSON library and is instead built to be able to have a swappable JSON encoding back-end. Back-ends are settable by calling Mustache::JSON.backend = :new_backend. You can also set it to a class, which simply expects that there be a class method encode that can be called with a Hash. Currently it defaults to the JSON gem but the following back-ends are available:

Note on Patches/Pull Requests

Copyright

Copyright © 2010 Intridea, Inc. and Michael Bleigh. See LICENSE for details.