class DictionaryLookup::Pearson

Constants

DEFAULT_DICTIONARY
VALID_DICTIONARIES

Public Class Methods

define(term, config) click to toggle source

Fetches term definitions from Pearson dictionary API

@param term [String] term to be defined @param config [Hash] configuration hash, for now supports :dictionary key.

For list of valid values see {DictionaryLookup::Pearson::VALID_DICTIONARIES}

@return [Array] an array of {DictionaryLookup::Definition} objects @raise SocketError if not connected to the internet

# File lib/PearsonLongman-Dictionary/pearson.rb, line 26
def self.define(term, config)
  dictionary = get_dictionary(config)

  url = "https://api.pearson.com/v2/dictionaries/#{dictionary}/entries?headword=#{term}"
  uri = URI(URI.escape(url))

  response = Net::HTTP.get(uri)
  data = JSON.parse(response)

  # Select definitions that match exactly with the term
  results = data["results"].select{ |d|
    d["headword"].downcase == term.downcase or d["headword"].downcase[0,term.length+1] == term.downcase + ","
  }
  definitions = []
  results.each do |result|
    headword = result["headword"]
    part_of_speech = result["part_of_speech"]
    entries = result["url"]
    # In wordwise dictionary, value of definition is String. Hence the is_a? test
    begin
    _definitions = result["senses"].first["definition"]
  rescue => e
  else
    denotation = _definitions.is_a?(Array) ? _definitions.first : _definitions
    if result["senses"].first["examples"].nil?
      examples = []
    else
      examples = result["senses"].first["examples"].map{|e| e["text"]}
    end
    if result["pronunciations"].nil?
      pronunciations = []
    else
    pronunciations = result["pronunciations"].first["audio"].map{|e| e["url"]}
    end
  end
    definitions << DictionaryLookup::Definition.new(headword, part_of_speech, denotation, examples, pronunciations, entries)
  end

  definitions
end
get_dictionary(config) click to toggle source

Helper method. Returns either a valid dictionary specified through config or the default dictionary

# File lib/PearsonLongman-Dictionary/pearson.rb, line 14
def self.get_dictionary(config)
  VALID_DICTIONARIES.include?(config[:dictionary]) ?
                            config[:dictionary] : DEFAULT_DICTIONARY
end