Class: FreeDictionaryApi::Client

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

Constant Summary collapse

BASE_URL =
'https://api.dictionaryapi.dev/api/v2/entries/en'.freeze
PARSER =
URI::Parser.new

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.lookup(word) ⇒ Object



14
15
16
# File 'lib/free_dictionary_api.rb', line 14

def self.lookup word
  self.new.lookup word
end

.lookup!(word) ⇒ Object



18
19
20
# File 'lib/free_dictionary_api.rb', line 18

def self.lookup! word
  self.new.lookup! word
end

Instance Method Details

#lookup(word) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/free_dictionary_api.rb', line 22

def lookup(word)
  encoded_word = PARSER.escape(word)
  uri = URI("#{BASE_URL}/#{encoded_word}")
  response = Net::HTTP.get_response(uri)

  case response
  when Net::HTTPSuccess
    parse_response(response.body)
  else
    handle_error(response)
  end
end

#lookup!(word) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/free_dictionary_api.rb', line 35

def lookup!(word)
  encoded_word = PARSER.escape(word)
  uri = URI("#{BASE_URL}/#{encoded_word}")
  response = Net::HTTP.get_response(uri)

  case response
  when Net::HTTPSuccess
    parse_response(response.body)
  else
    handle_error(response, true)
  end
end