Created
August 8, 2012 05:06
-
-
Save adambard/3292251 to your computer and use it in GitHub Desktop.
Franslate, the sinatra part
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
require 'sinatra' | |
require 'json' | |
require 'mustache' | |
## INITIALIZATION ########################## | |
configure do | |
LANGS_AVAILABLE = { | |
'de' => 'languages/de_20k_trans.txt', | |
'fr' => 'languages/fr_20k_trans.txt', | |
'pl' => 'languages/pl_20k_trans.txt', | |
'ru' => 'languages/ru_20k_trans.txt' | |
} | |
LEVELS_AVAILABLE = { | |
'beginner' => 100, | |
'intermediate' => 1000, | |
'advanced' => 10000 | |
} | |
@@langs = {} | |
LANGS_AVAILABLE.each { |lang, filename| | |
@@langs[lang] = {} | |
LEVELS_AVAILABLE.each { |diff, num| | |
@@langs[lang][diff] = {} | |
} | |
i = 0 | |
puts 'Loading ' + filename | |
File.open(filename) { |f| | |
f.each { |line| | |
tr, en = line.split(' ', 2) | |
if tr.strip.casecmp(en.strip) == 0 | |
next | |
end | |
if i < 100 | |
@@langs[lang]['beginner'][tr] = en; | |
end | |
if i < 1000 | |
@@langs[lang]['intermediate'][tr] = en; | |
end | |
@@langs[lang]['advanced'][tr] = en; | |
i += 1 | |
if i > 10000 | |
break | |
end | |
} | |
} | |
} | |
end | |
## HELPERS ############################################## | |
def get_question(lang, difficulty) | |
src_wordset = @@langs[lang][difficulty] | |
french_word = src_wordset.keys().sample | |
correct_option = src_wordset[french_word] | |
{ | |
'language' => lang, | |
'word' => french_word, | |
'correct_option' => correct_option, | |
'options' => (src_wordset.values().sample(4) + [correct_option]).shuffle.map{|i| {'name' => i}} | |
}.to_json | |
end | |
def render_template(tmpl_name) | |
Dir::chdir('templates'){ |d| | |
File.open(tmpl_name + '.mustache'){|f| | |
Mustache.render(f.read) | |
} | |
} | |
end | |
## VIEWS ################################## | |
get '/' do | |
render_template('index') | |
end | |
get '/about/' do | |
render_template('about') | |
end | |
get '/:lang/:difficulty/' do |lang, diff| | |
content_type :json | |
get_question(lang, diff) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment