]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
Move extensions to standard classes into a specific extends.rb util module
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # Extensions to standard classes, to be used by the various plugins
5 # Please note that global symbols have to be prefixed by :: because this plugin
6 # will be read into an anonymous module
7
8 # Extensions to the Array class
9 #
10 class ::Array
11
12   # This method returns a random element from the array, or nil if the array is
13   # empty
14   #
15   def pick_one
16     return nil if self.empty?
17     self[rand(self.length)]
18   end
19 end
20
21 # Extensions to the String class
22 #
23 # TODO make ircify_html() accept an Hash of options, and make riphtml() just
24 # call ircify_html() with stronger purify options.
25 #
26 class ::String
27
28   # This method will return a purified version of the receiver, with all HTML
29   # stripped off and some of it converted to IRC formatting
30   #
31   def ircify_html
32     txt = self
33
34     # bold and strong -> bold
35     txt.gsub!(/<\/?(?:b|strong)\s*>/, "#{Bold}")
36
37     # italic, emphasis and underline -> underline
38     txt.gsub!(/<\/?(?:i|em|u)\s*>/, "#{Underline}")
39
40     ## This would be a nice addition, but the results are horrible
41     ## Maybe make it configurable?
42     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
43
44     # Paragraph and br tags are converted to whitespace.
45     txt.gsub!(/<\/?(p|br)\s*\/?\s*>/, ' ')
46     txt.gsub!("\n", ' ')
47
48     # All other tags are just removed
49     txt.gsub!(/<[^>]+>/, '')
50
51     # Remove double formatting options, since they only waste bytes
52     txt.gsub!(/#{Bold}\s*#{Bold}/,"")
53     txt.gsub!(/#{Underline}\s*#{Underline}/,"")
54
55     # And finally whitespace is squeezed
56     txt.gsub!(/\s+/, ' ')
57
58     # Decode entities and strip whitespace
59     return Utils.decode_html_entities(txt).strip!
60   end
61
62   # This method will strip all HTML crud from the receiver
63   #
64   def riphtml
65     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
66   end
67 end
68
69