Skip to content

Instantly share code, notes, and snippets.

@Radagaisus
Created July 16, 2014 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Radagaisus/b9f3f2e8e2cac69249ba to your computer and use it in GitHub Desktop.
Save Radagaisus/b9f3f2e8e2cac69249ba to your computer and use it in GitHub Desktop.
A Sprockets Engine to write valid JSON in CoffeeScript
# 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