Class: WordsService
- Inherits:
-
Object
- Object
- WordsService
- Defined in:
- app/services/words_service.rb
Overview
Handles Datamuse API calls for dictionary and definition.
Class Method Summary collapse
-
.define(word) ⇒ String
This method returns the definition of a given word.
-
.word?(word) ⇒ Boolean
This method checks if a given word is valid.
-
.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.
Class Method Details
.define(word) ⇒ String
This method returns the definition of a given 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
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.
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 |