Class: Fy::Fanyi
- Inherits:
-
Object
- Object
- Fy::Fanyi
- Defined in:
- lib/fy/fanyi.rb
Instance Method Summary collapse
- #dict_explains ⇒ Object
-
#initialize(input) ⇒ Fanyi
constructor
A new instance of Fanyi.
- #query_for_hash ⇒ Object
- #result ⇒ Object
- #translations ⇒ Object
- #web_results ⇒ Object
- #word_and_phonetic ⇒ Object
-
#yd_result ⇒ Object
一般来说,有道词典解释的比较好 但是长一点的句子有道词典没有结果,需要用有道翻译 所以如果有道词典有结果就只用词典的结果,否则用有道翻译.
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_explains ⇒ Object
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_hash ⇒ Object
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 |
#result ⇒ Object
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 |
#translations ⇒ Object
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_results ⇒ Object
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_phonetic ⇒ Object
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_result ⇒ Object
一般来说,有道词典解释的比较好 但是长一点的句子有道词典没有结果,需要用有道翻译 所以如果有道词典有结果就只用词典的结果,否则用有道翻译
61 62 63 |
# File 'lib/fy/fanyi.rb', line 61 def yd_result @result_hash["basic"].nil? ? translations : dict_explains end |