module UrbanLookup
Urban Dictionary lookups for slang flip words.
Constants
- API_URL
- MAX_DEFINITION_CHARS
Public Instance Methods
Source
# File lib/urban_lookup.rb, line 54 def best_line(term, fetch: method(:default_fetch)) best_result(term, fetch: fetch)&.fetch(:line) rescue StandardError nil end
Source
# File lib/urban_lookup.rb, line 60 def best_result(term, fetch: method(:default_fetch)) token = term.to_s.strip.downcase return nil if token.length < 2 json = fetch.call(define_url(token)) entry = parse_response(json) return nil unless entry line = format_line(entry["word"].to_s.strip.empty? ? token : entry["word"], entry["definition"]) return nil unless line { line: line, thumbs_up: entry["thumbs_up"].to_i } rescue StandardError nil end
Source
# File lib/urban_lookup.rb, line 107 def card_body(term, fetch: method(:default_fetch)) line = best_line(term, fetch: fetch) return nil unless line { line: line, word: term.to_s.strip.downcase } end
Source
# File lib/urban_lookup.rb, line 18 def clean_definition(text) text.to_s .gsub(/\[|\]/, "") .gsub(/\s+/, " ") .strip end
Source
# File lib/urban_lookup.rb, line 103 def default_fetch(url) RabbotHttp.fetch_json(url) end
Source
# File lib/urban_lookup.rb, line 14 def define_url(term) "#{API_URL}?term=#{CGI.escape(term.to_s.strip)}" end
Source
# File lib/urban_lookup.rb, line 39 def format_line(term, definition_text) word = term.to_s.strip.downcase body = trim_definition(definition_text) return nil if word.empty? || body.empty? "#{word} — #{body}" end
Source
# File lib/urban_lookup.rb, line 47 def parse_response(json) data = json.is_a?(String) ? JSON.parse(json) : json pick_definition(data["list"]) rescue JSON::ParserError, StandardError nil end
Source
# File lib/urban_lookup.rb, line 32 def pick_definition(entries) list = Array(entries) return nil if list.empty? list.max_by { |entry| entry["thumbs_up"].to_i } end
Source
# File lib/urban_lookup.rb, line 25 def trim_definition(text, max_chars: MAX_DEFINITION_CHARS) cleaned = clean_definition(text) return cleaned if cleaned.length <= max_chars "#{cleaned[0, max_chars - 3].rstrip}..." end
Source
# File lib/urban_lookup.rb, line 76 def unique_lines(term, max: 5, fetch: method(:default_fetch)) token = term.to_s.strip.downcase return [] if token.length < 2 json = fetch.call(define_url(token)) data = json.is_a?(String) ? JSON.parse(json) : json entries = Array(data["list"]) return [] if entries.empty? seen = {} entries .sort_by { |entry| -entry["thumbs_up"].to_i } .filter_map do |entry| line = format_line(entry["word"].to_s.strip.empty? ? token : entry["word"], entry["definition"]) next unless line body = line.split(" — ", 2).last.to_s.strip.downcase next if body.empty? || seen[body] seen[body] = true line end .first(max) rescue JSON::ParserError, StandardError [] end