Created
April 26, 2010 19:45
-
-
Save qoobaa/379784 to your computer and use it in GitHub Desktop.
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
# /javascripts/i18n/:locale.js | |
# /javascripts/i18n/:locale.js | |
# /public/javascripts/i18n/:locale.js | |
require "json" | |
MINIFIED_LIB = <<EOJS | |
var I18n=I18n||(function(){function a(g,f){return g.replace(/\{\{([^}]+)\}\}/g,function(){return f[arguments[1]]||arguments[0]})}function c(f){if(!f){return[]}if(typeof f!="string"){return f}return f.split(".")}function d(g,j){var f=0,h=I18n.translations;j=(typeof j==="string")?[j]:(j||[]);while(g[f]){h=h&&h[g[f]];f++}if(h){return h}else{if(j.length===0){return null}else{if(j[0].substr(0,1)===":"){return d(g.slice(0,g.length-1).concat(c(j[0].substr(1))),j.slice(1))}else{return j[0]}}}}function b(g,f){if(f===undefined){return g}return f===1?g.one:g.other}function e(j,g){if(typeof j!="string"){var f=[],h;for(h=0;h<j.length;h++){f.push(e(j[h],g))}return f}else{g=g||{};g.defaultValue=g.defaultValue||null;j=c(g.scope).concat(c(j));var k=d(j,g.defaultValue);if(typeof k!=="string"&&k){k=b(k,g.count)}if(typeof k==="string"){k=a(k,g)}return k}}return{translate:e,t:e}})(); | |
EOJS | |
class RackjsMiddleware | |
def initialize(app, options = {}) | |
@options = options | |
@app = app | |
end | |
def call(env) | |
locale = chosen_locale(env) | |
if locale | |
write_cache(locale) | |
[200, {"Content-Type" => "application/javascript"}, compiled(locale)] | |
else | |
@app.call(env) | |
end | |
end | |
private | |
def path | |
@options.fetch(:path, "/javascripts/i18n") | |
end | |
def cache_path | |
@options.fetch(:cache_path, "public") | |
end | |
def cache? | |
[email protected](:cache, false) | |
end | |
def translations | |
I18n.backend.send(:init_translations) if I18n.backend.send(:translations).empty? | |
I18n.backend.send(:translations) | |
end | |
def available_locales | |
translations.keys | |
end | |
def write_cache(locale) | |
# File.join(cache_path, path) | |
# FileUtils.mkdir_p(cache_path) | |
# File.open("public/javascripts/i18n/#{locale}.js", "wb") { |file| file.write(compiled(locale)) } | |
end | |
def compiled(locale) | |
"I18n.locale=I18n.locale||\"#{locale}\";I18n.translations=I18n.translations||#{translations[locale].to_json};#{MINIFIED_LIB}" | |
end | |
def path_regexp | |
%r{^/javascripts/i18n/(#{available_locales.join("|")}).js$} | |
end | |
def chosen_locale(env) | |
unless available_locales.empty? | |
match_data = path_regexp.match(env["path_info"]) | |
match_data && match_data[1].to_sym | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment