Sha256: 3b1b79029405c547aec9078b95b606d576d8c99f0952d968eea5a9c2ea992bf5

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

require 'net/http'

module TheFreeDictionary
  class Dictionary
    attr_accessor :language, :region

    def find(statement)
      uri = build_uri(statement)
      response = fetch(uri)
      sound = build_sound_url(response)
      transcription = fetch_transcription(response)

      { sound:, transcription: }
    end

    private

    def fetch(uri)
      Net::HTTP.get_response(uri)
    rescue Socket::ResolutionError
      nil
    end

    def build_uri(statement)
      URI(URI::DEFAULT_PARSER.escape("https://#{@language}.thefreedictionary.com/#{statement}"))
    end

    def build_sound_url(response)
      sound_data = response.body.match(%r{#{@language}/#{@region}[^"]+})
      if sound_data.nil?
        ''
      else
        "https://img2.tfd.com/pron/mp3/#{sound_data[0]}.mp3"
      end
    end

    def fetch_transcription(response)
      regex = %r{<span[^>]*onclick="pron_key\(1\)"[^>]*class="pron"[^>]*>\s*\(?([^)]+)\)?\s*</span>}
      transcription_data = response.body.match(regex)
      if transcription_data.nil?
        ''
      else
        decode_html_entities(transcription_data[1].force_encoding('UTF-8'))
      end
    end

    def decode_html_entities(string)
      string.gsub(/&#(\d+);/) { |_match| ::Regexp.last_match(1).to_i.chr(Encoding::UTF_8) }
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
the-free-dictionary-0.0.3 lib/the_free_dictionary/dictionary.rb
the-free-dictionary-0.0.2 lib/the_free_dictionary/dictionary.rb
the-free-dictionary-0.0.1 lib/the_free_dictionary/dictionary.rb