Class: Dephine::Dictionary

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(word) ⇒ Dictionary

Public: Initialize some definitions of a word.

word - A String to be defined.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/dephine/dictionary.rb', line 12

def initialize(word)
  raise ArgumentError, "Word shouldn't be blank" if word.empty?

  @meanings = []
  @pronunciations = []
  url = "https://www.google.com/dictionary/json?callback=define&q=#{word}&" \
  "sl=en&tl=en&restrict=pr%2Cde&client=te"

  # fetch and parse the json document
  content = JSON.parse(open(url).read[7..-11])

  content['primaries'].each do |primary|
    @meanings << {
      type: primary['terms'][0]['labels'][0]['text'],
      phonetic: primary['terms'][1]['text'],
      meanings: []
    }

    # add pronunciation
    primary['terms'].each do |term|
      if term['type'] == 'sound'
        @pronunciations << {
          url: term['text'],
        }
      end
    end

    # add meanings
    primary['entries'].each do |entry|
      @meanings[-1][:meanings] << {
        text: entry['terms'][0]['text'].gsub('x27', "'") \
          .gsub(/x3.*?3e/, ''),
        examples: []
      }

      # add examples of a meaning
      if entry.has_key?('entries')
        entry['entries'].each do |eg|
          @meanings[-1][:meanings][-1][:examples] << eg['terms'][0]['text'] \
            .gsub('x27', "'").gsub(/x3.*?3e/, '')
        end
      end

    end if primary.has_key?('entries')
  end if content.has_key?('primaries')
end

Instance Attribute Details

#meaningsObject (readonly)

Public: Returns the Array meanings of the word.



7
8
9
# File 'lib/dephine/dictionary.rb', line 7

def meanings
  @meanings
end

#pronunciationsObject (readonly)

Public: Returns the Array meanings of the word.



7
8
9
# File 'lib/dephine/dictionary.rb', line 7

def pronunciations
  @pronunciations
end