Skip to content

Instantly share code, notes, and snippets.

@valachi
Created April 1, 2013 15:13
Show Gist options
  • Save valachi/5285483 to your computer and use it in GitHub Desktop.
Save valachi/5285483 to your computer and use it in GitHub Desktop.
module Translator
extend self
URL = "top secret"
PARTS_OF_SPEECH = %w(noun verb adjective article pronoun conjunction preposition)
def fetch(word)
formatted (JSON (with_encoding_for (translated (URI.escape word))))
end
private
delegate :get, to: RestClient
def translated(word)
puts "#{URL}#{word}"
get URL + word
end
def with_encoding_for(raw_data)
raw_data.encode 'utf-8', 'koi8-r'
end
# data = JSON((Translator.send :translated, 'dog').force_encoding('windows-1251').encode('utf-8'))
def formatted(data)
if phrase?(data)
collect_phrase(data)
else
translation = find_parts_of_speech(data) << find_sentence(data)
translation.map { |word| word.mb_chars.downcase.to_s }
.uniq
.delete_if { |word| word.empty? }.join(', ')
end
end
def find_parts_of_speech(data, types = PARTS_OF_SPEECH)
translation = []
types.each do |type|
found = dictionary(data).find do |hash|
hash['pos'] == type
end
translation << (found || {}).fetch('terms', '')[0...5]
end
translation.flatten
end
def find_sentence(data)
data.fetch('sentences').first['trans']
end
def dictionary(data)
data.fetch 'dict', []
end
def collect_phrase(data)
data.fetch('sentences', []).map{|hash| hash['trans']}.join
end
def phrase?(data)
dictionary(data).empty?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment