Skip to content

Instantly share code, notes, and snippets.

@MaxLap
Last active December 25, 2015 20:08
Show Gist options
  • Save MaxLap/7032239 to your computer and use it in GitHub Desktop.
Save MaxLap/7032239 to your computer and use it in GitHub Desktop.
Helper to allow passing locales to :coffeescript filters and javascript filters if you wrap your javascript in (function() { ... without having to use interpolation, saving you against slow rendering on Windows servers.
module HamlHelper
def coffee_with_locals locals={}, &block
# This helper will set locals as values inside of the :coffeescript filter that follows.
# Doing this instead of using regular interpolation allows haml to keep a compiled version of the CoffeeScript
# instead of having to compile on every render after the interpolation is applied. On Linux, the impact is
# negligible because V8 is fast, but Windows environments don't have this chance and page rendering can be slowed
# heavily from having to compile CoffeeScript.
block_content = capture_haml do
block.call
end
return block_content if locals.blank?
javascript_locals = "\nvar "
javascript_locals << locals.map{ |key, value| j(key.to_s) + ' = ' + value.to_json.gsub('</', '<\/') }.join(",\n ")
javascript_locals << ";\n"
content_node = Nokogiri::HTML::DocumentFragment.parse(block_content)
content_node.search('script').each do |script_tag|
# This will match the '(function() {' at the start of coffeescript's compiled code
split_coffee = script_tag.content.partition(/\(\s*function\s*\(\s*\)\s*\{/)
script_tag.content = split_coffee[0] + split_coffee[1] + javascript_locals + split_coffee[2]
end
content_node.to_s.html_safe
end
end
= coffee_with_locals "test" => "hello ", :something => ["monde", "mundo", "world"], :signs => {:interogation => "?", :exclamation => "!"} do
:coffeescript
alert(test + something[2] + signs['exclamation'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment