Skip to content

Instantly share code, notes, and snippets.

@avishai
Created August 2, 2011 08:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avishai/1119787 to your computer and use it in GitHub Desktop.
Save avishai/1119787 to your computer and use it in GitHub Desktop.
Milamix Application
# Milamix app - Translate phrases into multiple languages at once
# http://milamix.heroku.com
# Copyright (c) 2011 Avishai Weiss (avishai dot weiss at gmail dot com)
require "rubygems"
require "sinatra"
require "open-uri"
require "json"
API_KEY = "GOOGLE API KEY GOES HERE"
BASE_URL = "https://www.googleapis.com/language/translate/v2?key=#{API_KEY}"
def translate(text, source = 'en', target = 'es')
url = BASE_URL + "&q=#{text}&source=#{source}&target=#{target}"
results = JSON::parse open(URI.parse(URI.encode(url.strip))).read
results['data']['translations'][0]['translatedText']
end
get '/' do
erb :index
end
post '/translate.json' do
content_type "application/json"
text = params[:q]
source = params[:source] || 'en'
targets = params[:targets] || ['es', 'pt']
@translations = {}
targets.each do |target|
@translations[target] = translate(text, source, target)
end
@translations.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment