Created
September 15, 2009 14:49
-
-
Save richardtifelt/187345 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
require 'httparty' | |
module DetectLanguage | |
class GoogleTranslate | |
include HTTParty | |
base_uri 'http://ajax.googleapis.com/ajax/services/language' | |
format(:json) | |
def self.detect_language str | |
options = {:query => {:q => str, :v => "1.0"}} | |
result = get("/detect", options) | |
DetectResult.new(result) | |
end | |
def self.translate str, to, from = nil | |
options = {:query => {:q => str, :langpair => "#{from}|#{to}", :v => "1.0"}} | |
result = get("/translate", options) | |
result["responseData"] ? result["responseData"]["translatedText"] : nil | |
end | |
end | |
class DetectResult | |
def initialize result | |
#[TODO: Hantera respons status] | |
# NOTE: Sometimes, if the text is really cryptic, Google will return an empty responseData. Let's | |
# avoid this leading to nil.[] exceptions by defaulting to an empty hash. | |
@responseData = result["responseData"] || {} | |
end | |
def locale | |
@responseData["language"] | |
end | |
def is_reliable? | |
@responseData["isReliable"] ? true : false | |
end | |
def confidence | |
@responseData["confidence"] | |
end | |
end | |
end | |
class String | |
def detect_language | |
DetectLanguage::GoogleTranslate.detect_language self | |
end | |
def translate to, from = nil | |
DetectLanguage::GoogleTranslate.translate(self, to, from) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment