Created
July 16, 2014 00:02
-
-
Save Radagaisus/b9f3f2e8e2cac69249ba to your computer and use it in GitHub Desktop.
A Sprockets Engine to write valid JSON in CoffeeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The CoffeeScriptJSON module is a Sprockets engine that can be used to write | |
# JSON files in CoffeeScript. | |
# | |
# This CoffeeScript: | |
# | |
# # whatever.json.coffee_json | |
# hello: 'world!' | |
# | |
# Will be compiled down to: | |
# | |
# { | |
# "hello": 'world!' | |
# } | |
# | |
# | |
module CoffeeScriptJSON | |
class Template < Tilt::CoffeeScriptTemplate | |
# Prepares the template. We override `prepare` so we can add the `bare` option | |
# to the compilation, to remove the CoffeeScript closure. | |
def prepare | |
super | |
options[:bare] = true | |
end | |
# Evaluate the template. We override `evaluate` so we can convert the outputted | |
# JavaScript into valid JSON. | |
def evaluate(scope, locals, &block) | |
super | |
# (1) Remove the leading and trailing parantheses and semicolon (2) Evaluate as | |
# JavaScript to get a Hash (3) Convert it to pretty printed JSON. | |
@output = JSON.pretty_generate(ExecJS.eval(@output.gsub(/(\A\(|\);\Z)/, ''))) | |
end | |
end | |
end | |
# Register the `CoffeeScriptJSON` engine for the `.coffee_json` file extension. | |
Rails.application.assets.register_engine '.coffee_json', CoffeeScriptJSON::Template |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment