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
-
.format_results(results, color = true) ⇒ String
Format results for output.
-
.open_url(term = '') ⇒ Nil
Open the search URL in the user’s browser.
-
.query(term, *opts) ⇒ Array<Hash>
Query the website and return a list of definitions for the provided term.
-
.search_url(term = '', api = true) ⇒ String
Get the search URL to query for a given term.
-
.version ⇒ String
The current gem’s version.
Class Method Details
.format_results(results, color = true) ⇒ String
Format results for output
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
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.
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.
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 |
.version ⇒ String
Returns the current gem’s version.
15 16 17 |
# File 'lib/ud.rb', line 15 def version '0.2.5' end |