Created
October 15, 2009 06:49
-
-
Save kossnocorp/210738 to your computer and use it in GitHub Desktop.
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
# Hi! I'am rack middleware! | |
# I was born for return to you valid js on json i18n objects | |
# My author's name was Aleksandr Koss. Mail him at kossnocorp@gmail.com | |
# Nice to MIT you! | |
class I18nJs | |
def initialize app, options = {} | |
@app = app | |
@options = options | |
end | |
def call env | |
# Valid url is /i18n-<i18n key>-<locale>.<format> where | |
# i18n key - yaml branch named "locale.key" | |
# locale - locale as is | |
# format - js or json | |
if data_array = env['PATH_INFO'].scan( \ | |
/^\/i18n-(\w+)-(\w{1,3})[.](js[on]*)$/)[0] | |
key, locale, type = data_array | |
# Return if :accepted_keys not :all and | |
# not included in :accepted_keys array | |
return @app.call env if \ | |
@options[:accepted_keys] and | |
@options[:accepted_keys] != :all and | |
not @options[:accepted_keys].include? key.to_sym # Key don't accepted | |
# Get yaml branch by key | |
json = YAML::load( | |
File.open(File.dirname(__FILE__) + | |
"/../config/locales/#{locale}.yml" | |
))[locale][key].to_json | |
return @app.call env if json == 'null' # Branch not found | |
content_type, response = type == 'js' ? | |
['application/javascript', "var i18n_#{key} = [#{json}];"] : | |
['application/json', json] | |
[200, {'Content-Type' => content_type}, [response]] | |
else | |
@app.call env | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment