A simple addition to Mustache that adds easy JSON serialization.
Ruby
Switch branches/tags
Pull request Compare This branch is 2 commits ahead of mobomo:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.document
.gitignore
LICENSE
README.rdoc
Rakefile
VERSION
mustache_json.gemspec

README.rdoc

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:

  • JSON Gem (:json_gem)

  • JSON Pure (:json_pure)

  • ActiveSupport (:active_support)

  • YAJL Ruby (:yajl)

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don't break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request.

Copyright

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