Class: Fy::Fanyi

Inherits:
Object
  • Object
show all
Defined in:
lib/fy/fanyi.rb

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Fanyi

Returns a new instance of Fanyi.



11
12
13
14
# File 'lib/fy/fanyi.rb', line 11

def initialize(input)
  @words = input
  query_for_hash
end

Instance Method Details

#dict_explainsObject



37
38
39
40
41
42
43
# File 'lib/fy/fanyi.rb', line 37

def dict_explains
  dict_explains = @result_hash["basic"]["explains"] if @result_hash["basic"]
  lines         = dict_explains.collect do |explain|
    " - " + explain.color(:green)
  end
  lines << ""
end

#query_for_hashObject



16
17
18
19
20
# File 'lib/fy/fanyi.rb', line 16

def query_for_hash
  query_url    = API_URL + URI.escape(@words.gsub(/ /, '+'))
  result_json  = Net::HTTP.get(URI(query_url))
  @result_hash = JSON.parse(result_json)
end

#resultObject



65
66
67
68
69
# File 'lib/fy/fanyi.rb', line 65

def result
  output = []
  output << word_and_phonetic << yd_result << web_results
  output.flatten
end

#translationsObject



22
23
24
25
26
27
28
# File 'lib/fy/fanyi.rb', line 22

def translations
  translations = @result_hash["translation"]
  lines        = translations.collect do |translation|
    "  " + translation.color(:green)
  end
  lines << ""
end

#web_resultsObject



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fy/fanyi.rb', line 45

def web_results
  return [] unless @result_hash["web"]
  lines       = []
  web_results = @result_hash["web"]
  web_results.each_with_index do |web_result, i|
    web_result_key   = web_result["key"].gsub(/#{@words}/i, @words.color(:yellow))
    web_result_value = web_result["value"].join(', ').color(:cyan)
    lines << " #{i+1}. #{web_result_key}"
    lines << "    #{web_result_value}"
  end
  lines << ""
end

#word_and_phoneticObject



30
31
32
33
34
35
# File 'lib/fy/fanyi.rb', line 30

def word_and_phonetic
  line     = " " + @words
  phonetic = @result_hash["basic"]["phonetic"] if @result_hash["basic"]
  line     += " [ #{phonetic} ]".color(:magenta) if phonetic
  [line, ""]
end

#yd_resultObject

一般来说,有道词典解释的比较好 但是长一点的句子有道词典没有结果,需要用有道翻译 所以如果有道词典有结果就只用词典的结果,否则用有道翻译



61
62
63
# File 'lib/fy/fanyi.rb', line 61

def yd_result
  @result_hash["basic"].nil? ? translations : dict_explains
end