-
-
Save sishen/2360781 to your computer and use it in GitHub Desktop.
CleanEcoTemplate for Sprockets in Rails app
This file contains hidden or 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
# Put this file in lib/ | |
require 'sprockets/eco_template' | |
class CleanEcoTemplate < Sprockets::EcoTemplate | |
FROM = " (function() {" | |
TO = "}).call(__obj);" | |
def evaluate(scope, locals, &block) | |
content = Eco.compile(data) | |
from = content.index(FROM) | |
to = content.rindex(TO) | |
content = content[from...to] + TO | |
<<-JS | |
function(__obj) { | |
if (!__obj) __obj = {}; | |
var __helpers = window.ecoHelpers; | |
var __out = []; | |
var __sanitize = __helpers.sanitize; | |
var __capture = __helpers.captureFor(__obj, __out); | |
var __rememberSafe = __obj.safe; | |
var __rememberEscape = __obj.escape; | |
__obj.safe = __helpers.safe; | |
__obj.escape = __helpers.escape; | |
#{content} | |
__obj.safe = __rememberSafe; | |
__obj.escape = __rememberEscape; | |
return __out.join(''); | |
}; | |
JS | |
end | |
end |
This file contains hidden or 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
# Must include eco-helpers.js before eco files | |
(function(global) { | |
var ecoHelpers = { | |
sanitize: function(value) { | |
if (value && value.ecoSafe) { | |
return value; | |
} else if (typeof value !== 'undefined' && value != null) { | |
return ecoHelpers.escape(value); | |
} else { | |
return ''; | |
} | |
}, | |
safe: function(value) { | |
if (value && value.ecoSafe) { | |
return value; | |
} else { | |
if (!(typeof value !== 'undefined' && value != null)) value = ''; | |
var result = new String(value); | |
result.ecoSafe = true; | |
return result; | |
} | |
}, | |
escape: function(value) { | |
return ('' + value) | |
.replace(/&/g, '&') | |
.replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/"/g, '"'); | |
}, | |
captureFor: function(obj, out) { | |
return (function(callback) { | |
var length = out.length; | |
callback.call(obj); | |
return ecoHelpers.safe(out.splice(length, out.length - length).join('')); | |
}); | |
} | |
}; | |
global.ecoHelpers = ecoHelpers; | |
})(window); |
This file contains hidden or 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
# Put this file in config/initializers | |
require 'clean_eco_template' | |
Rails.application.assets.register_engine '.eco', CleanEcoTemplate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment