Class: BingDictionary::Base

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(word, options = {}) ⇒ Base



17
18
19
20
21
# File 'lib/bing_dictionary.rb', line 17

def initialize(word, options = {})
  file = open("http://cn.bing.com/dict/?q=#{CGI::escape(word)}")
  @doc = Nokogiri::HTML(file)
  @options = options
end

Instance Attribute Details

#docObject (readonly)

Returns the value of attribute doc.



8
9
10
# File 'lib/bing_dictionary.rb', line 8

def doc
  @doc
end

Class Method Details

.translate(word, options = {}) ⇒ Object



10
11
12
13
14
15
# File 'lib/bing_dictionary.rb', line 10

def self.translate(word, options = {})
  self.new(word, options).translate
rescue SocketError
  warn 'Connection failed! Please check your network.'
  exit 1
end

Instance Method Details

#guessObject



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bing_dictionary.rb', line 61

def guess
  puts
  content = doc.at_css('.content')
  puts content.at_css('.p2-2').text
  puts

  content.css('.dym_area').each do |area|
      puts area.at_css('.df_wb_a').text
      puts area.css('.df_wb_c').map(&:text)
      puts
  end
end

#headObject



31
32
33
34
35
36
37
38
# File 'lib/bing_dictionary.rb', line 31

def head
  puts doc.at_css('#headword').text
  puts doc.at_css('.hd_tf_lh').text.green
  puts
  doc.at_css('.hd_area').next_sibling.css('li').each do |li|
    puts li.at_css('.pos').text.fixed(5).blue + li.at_css('.def').text
  end
end

#machineObject



46
47
48
49
50
# File 'lib/bing_dictionary.rb', line 46

def machine
  puts doc.at_css('.smt_hw').text
  puts doc.at_css('.p1-10').text
  puts doc.at_css('.p1-11').text.green
end

#pronounceObject



40
41
42
43
44
# File 'lib/bing_dictionary.rb', line 40

def pronounce
  url = doc.at_css('.hd_tf_lh .hd_tf a').attr('onclick').match(/http.*mp3/)
  `curl -o /tmp/dict.mp3 #{url} &> /dev/null`
  `afplay /tmp/dict.mp3`
end

#sentenceObject



52
53
54
55
56
57
58
59
# File 'lib/bing_dictionary.rb', line 52

def sentence
  puts
  doc.css('#sentenceSeg .se_li').first(4).map do |li|
    puts li.css('.sen_en').text
    puts li.css('.sen_cn').text
    puts
  end
end

#translateObject



23
24
25
26
27
28
29
# File 'lib/bing_dictionary.rb', line 23

def translate
  head if doc.at_css('#headword')
  machine if doc.at_css('.smt_hw')
  sentence if doc.at_css('#sentenceSeg .se_li')
  guess if doc.at_css('.dym_area')
  pronounce if doc.at_css('#headword') && @options[:pronounce]
end