Class: Cinch::Plugins::UrbanDictionary

Inherits:
Object
  • Object
show all
Includes:
Cinch::Plugin
Defined in:
lib/cinch/plugins/urbandictionary.rb

Instance Method Summary collapse

Instance Method Details

#awesome_truncate(text, length = 30, truncate_string = "...") ⇒ Object


35
36
37
38
39
# File 'lib/cinch/plugins/urbandictionary.rb', line 35

def awesome_truncate(text, length = 30, truncate_string = "...")
  return if text.nil?
  l = length - truncate_string.bytesize
  text.bytesize > length ? text[/\A.{#{l}}\w*\;?/m][/.*[\w\;]/m] + truncate_string : text
end

#execute(m, word) ⇒ Object


41
42
43
# File 'lib/cinch/plugins/urbandictionary.rb', line 41

def execute(m, word)
  m.reply(lookup(word, m.channel.name, m.user.nick) || "No results found", false)
end

#lookup(word, channel, nick) ⇒ Object


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cinch/plugins/urbandictionary.rb', line 14

def lookup(word, channel, nick)
  begin
    url = "http://www.urbandictionary.com/define.php?term=#{CGI.escape(word)}";
    o = Nokogiri::HTML(open(url));
    defword = CGI.unescape_html o.at("td.word").text.gsub(/\s+/, ' ');
    definition = CGI.unescape_html o.at("div.definition").text.gsub(/\s+/, ' ');
    #output = "#{defword.strip} -- #{definition.gsub(/^(.{#{510 - (": PRIVMSG :").bytesize - defword.strip.bytesize - url.bytesize - 16}}[^\s]*)(.*)/m) {$2.empty? ? $1 : $1 + '...'}} (#{url})";

    #Determining truncation length:
    tlen = 510 - (": PRIVMSG :").bytesize
    tlen = tlen - bot.mask.to_s.length - (channel || nick).length
    tlen = tlen - defword.strip.bytesize - url.bytesize - 10

    output = "#{defword.strip} -- #{awesome_truncate(definition, tlen)} (#{url})";
    definition != nil ? output : nil;
  rescue
    puts "#{$!}"
    nil
  end
end