Sha256: fce0121b11fab1515108c53fd69281e585a852ae00dc6f04f78ff50de584696e

Contents?: true

Size: 797 Bytes

Versions: 1

Compression:

Stored size: 797 Bytes

Contents

require 'nokogiri'
require 'open-uri'

module UrbanDictionary
  class Word
    attr_reader :word, :entries

    # Can raise SocketError if unable to connect to specified URL
    def self.from_url(url)
      html = open(url).read
      doc = Nokogiri::HTML(html)

      if doc.css('.word').any?
        word = doc.css('.word').first.content.strip
        definitions = doc.css('.definition').map{|d| d.content.strip }
        examples = doc.css('.example').map{|e| e.content.strip }
        entries = definitions.zip(examples).map{|d,e| Entry.new(d, e)}

        Word.new(word, entries)
      end
    end

    def initialize(word, entries)
      @word = word
      @entries = entries
    end

    def to_s
      @word
    end

    def size
      @word.size
    end
    alias :length :size
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
urban_dictionary-0.0.2 lib/urban_dictionary/word.rb