Module: UD

Defined in:
lib/ud.rb,
lib/ud/formatting.rb

Overview

This module provide some methods to scrape definitions from the Urban Dictionary website.

Defined Under Namespace

Modules: Formatting

Class Method Summary collapse

Class Method Details

.format_results(results, color = true) ⇒ String

Format results for output

Parameters:

  • results (Array)

    this must be an array of results, as returned by UD.query.

  • color (Boolean) (defaults to: true)

    colored output

Returns:

  • (String)


79
80
81
# File 'lib/ud.rb', line 79

def format_results(results, color=true)
  UD::Formatting.text(results, color)
end

.open_url(term = '') ⇒ Nil

Open the search URL in the user’s browser

Parameters:

  • term (String) (defaults to: '')

    the term to search for. It must be a string, spaces are allowed.

Returns:

  • (Nil)


38
39
40
# File 'lib/ud.rb', line 38

def open_url(term='')
  system open_cmd, search_url(term, false)
end

.query(term, *opts) ⇒ Array<Hash>

Query the website and return a list of definitions for the provided term. This list may be empty if there’s no result.

Parameters:

  • term (String)

    the term to search for

  • opts (Hash)

    options. This is used by the command-line tool. :count is the maximum number of results to return, :ratio is the minimum upvotes/downvotes ratio. Other options may be added in the future.

Returns:

  • (Array<Hash>)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ud.rb', line 50

def query(term, *opts)

  opts = {:count => 1, :ratio => 0.0}.merge(opts[0] || {})

  return [] if opts[:count] <= 0

  resp = JSON.parse(open(search_url term).read, :symbolize_names => true)

  resp[:list].map do |res|
    {
      :id         => res[:defid],
      :word       => res[:word],
      :author     => res[:author],
      :permalink  => res[:permalink],
      :definition => res[:definition].strip,
      :example    => res[:example].strip,
      :upvotes    => res[:thumbs_up],
      :downvotes  => res[:thumbs_down]
    }
  end.keep_if do |d|
    d[:upvotes]/[d[:downvotes], 0.1].max.to_f >= opts[:ratio]
  end.take opts[:count]
end

.search_url(term = '', api = true) ⇒ String

Get the search URL to query for a given term.

Parameters:

  • term (String) (defaults to: '')

    the term to search for. It must be a string, spaces are allowed.

  • api (Boolean) (defaults to: true)

    truthy if the API URL should be used.

Returns:

  • (String)


24
25
26
27
28
29
30
31
32
# File 'lib/ud.rb', line 24

def search_url(term='', api=true)
  param = URI.encode_www_form('term' => term)

  if api
    "http://api.urbandictionary.com/v0/define?#{param}"
  else
    "http://www.urbandictionary.com/define.php?#{param}"
  end
end

.versionString

Returns the current gem’s version.

Returns:

  • (String)

    the current gem’s version



15
16
17
# File 'lib/ud.rb', line 15

def version
  '0.2.5'
end