Class: WordsService

Inherits:
Object
  • Object
show all
Defined in:
app/services/words_service.rb

Overview

Handles Datamuse API calls for dictionary and definition.

Class Method Summary collapse

Class Method Details

.define(word) ⇒ String

This method returns the definition of a given word

Examples:

"WordsService.define("chair")" #=> "n\tAn item of furniture used to sit on or in, comprising a seat, legs or wheels, back, and sometimes arm rests, for use by one person. Compare stool, couch, sofa, settee, loveseat and bench."

Parameters:

  • word (String)

    you want definition for

Returns:

  • (String)

    definiton of word



11
12
13
14
15
16
17
18
19
20
21
# File 'app/services/words_service.rb', line 11

def self.define(word)
  uri = URI("https://api.datamuse.com/words?sp=#{word}&md=d&max=1")
  response = Net::HTTP.get(uri)
  info = JSON.parse(response)
  return false if info.empty?
  if info[0]["word"].casecmp(word).zero? && info[0].key?("defs")
    info[0]["defs"][0]
  else
    ""
  end
end

.word?(word) ⇒ Boolean

This method checks if a given word is valid

Examples:

"WordsService.word?("happy")" #=> True
"WordsService.word?("aaeer")" #=> False

Parameters:

  • word (String)

    to be checked for validity

Returns:

  • (Boolean)

    based on frequency per one million words



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/services/words_service.rb', line 50

def self.word?(word)
  uri = URI("https://api.datamuse.com/words?sp=#{word}&md=f&max=1")
  response = Net::HTTP.get(uri)
  info = JSON.parse(response)

  if info.empty?
    false
  elsif info[0]["word"].upcase == word.upcase
    frequency = info[0]["tags"][0][/\d+\.\d+/].to_f
    return true if frequency > 0.4
  end

  false
end

.words(letters, start_with_first = false) ⇒ Array<String>

This method returns the list of valid words that can be formed by a given sequence of letters.

Examples:

"WordsService.words("aruchit")" #=> ["catch", "chair", "chart", "tacit", ... ]

Parameters:

  • letters (String)

    sequence of letters

  • start_with_first (Boolean) (defaults to: false)

    optionally require that the first letter passed in should be the first letter for all words.

Returns:

  • (Array<String>)

    list of valid words that always include the first character of letters



30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/services/words_service.rb', line 30

def self.words(letters, start_with_first = false)
  uri = URI("https://api.datamuse.com/words?sp=#{URI.encode_www_form_component("#{start_with_first ? "" : "*"}#{letters[0]}*+#{letters}")}&md=f")
  response = Net::HTTP.get(uri)
  words = JSON.parse(response)

  usable_words = words.select do |word_data|
    frequency = word_data["tags"][0][/\d+\.\d+/].to_f
    word_data["word"].length > 3 && frequency > 0.5 && word_data["word"] =~ /^[a-zA-Z]+$/
  end.map { |word_data| word_data["word"] }

  usable_words
end