]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
extends: pick_one and rand methods for Range
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Standard classes extensions
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2006,2007 Giuseppe Bilotta
8 # License:: GPL v2
9 #
10 # This file collects extensions to standard Ruby classes and to some core rbot
11 # classes to be used by the various plugins
12 #
13 # Please note that global symbols have to be prefixed by :: because this plugin
14 # will be read into an anonymous module
15
16
17 # Extensions to the Array class
18 #
19 class ::Array
20
21   # This method returns a random element from the array, or nil if the array is
22   # empty
23   #
24   def pick_one
25     return nil if self.empty?
26     self[rand(self.length)]
27   end
28 end
29
30 # Extensions to the Range class
31 #
32 class ::Range
33
34   # This method returns a random number between the lower and upper bound
35   #
36   def pick_one
37     len = self.last - self.first
38     len += 1 unless self.exclude_end?
39     self.first + Kernel::rand(len)
40   end
41   alias :rand :pick_one
42 end
43
44 # Extensions for the Numeric classes
45 #
46 class ::Numeric
47
48   # This method forces a real number to be not more than a given positive
49   # number or not less than a given positive number, or between two any given
50   # numbers
51   #
52   def clip(left,right=0)
53     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
54     l = [left,right].min
55     u = [left,right].max
56     return l if self < l
57     return u if self > u
58     return self
59   end
60 end
61
62 # Extensions to the String class
63 #
64 # TODO make ircify_html() accept an Hash of options, and make riphtml() just
65 # call ircify_html() with stronger purify options.
66 #
67 class ::String
68
69   # This method will return a purified version of the receiver, with all HTML
70   # stripped off and some of it converted to IRC formatting
71   #
72   def ircify_html(opts={})
73     txt = self.dup
74
75     # remove scripts
76     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
77
78     # remove styles
79     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
80
81     # bold and strong -> bold
82     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
83
84     # italic, emphasis and underline -> underline
85     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
86
87     ## This would be a nice addition, but the results are horrible
88     ## Maybe make it configurable?
89     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
90     case val = opts[:a_href]
91     when Reverse, Bold, Underline
92       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
93     when :link_out
94       # Not good for nested links, but the best we can do without something like hpricot
95       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
96         debug match
97         debug [$1, $2, $3, $4].inspect
98         link = $1 || $2 || $3
99         str = $4
100         str + ": " + link
101       }
102     else
103       warn "unknown :a_href option #{val} passed to ircify_html" if val
104     end
105
106     # Paragraph and br tags are converted to whitespace
107     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
108     txt.gsub!("\n", ' ')
109     txt.gsub!("\r", ' ')
110
111     # Superscripts and subscripts are turned into ^{...} and _{...}
112     # where the {} are omitted for single characters
113     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
114     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
115     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
116
117     # All other tags are just removed
118     txt.gsub!(/<[^>]+>/, '')
119
120     # Convert HTML entities. We do it now to be able to handle stuff
121     # such as &nbsp;
122     txt = Utils.decode_html_entities(txt)
123
124     # Remove double formatting options, since they only waste bytes
125     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
126     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
127
128     # Simplify whitespace that appears on both sides of a formatting option
129     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
130     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
131     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
132
133     # And finally whitespace is squeezed
134     txt.gsub!(/\s+/, ' ')
135
136     # Decode entities and strip whitespace
137     return txt.strip
138   end
139
140   # As above, but modify the receiver
141   #
142   def ircify_html!(opts={})
143     old_hash = self.hash
144     replace self.ircify_html(opts)
145     return self unless self.hash == old_hash
146   end
147
148   # This method will strip all HTML crud from the receiver
149   #
150   def riphtml
151     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
152   end
153 end
154
155
156 # Extensions to the Regexp class, with some common and/or complex regular
157 # expressions.
158 #
159 class ::Regexp
160
161   # A method to build a regexp that matches a list of something separated by
162   # optional commas and/or the word "and", an optionally repeated prefix,
163   # and whitespace.
164   def Regexp.new_list(reg, pfx = "")
165     if pfx.kind_of?(String) and pfx.empty?
166       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
167     else
168       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
169     end
170   end
171
172   IN_ON = /in|on/
173
174   module Irc
175     # Match a list of channel anmes separated by optional commas, whitespace
176     # and optionally the word "and"
177     CHAN_LIST = Regexp.new_list(GEN_CHAN)
178
179     # Match "in #channel" or "on #channel" and/or "in private" (optionally
180     # shortened to "in pvt"), returning the channel name or the word 'private'
181     # or 'pvt' as capture
182     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
183     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
184
185     # As above, but with channel lists
186     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
187     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
188     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
189     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
190
191     # Match a list of nicknames separated by optional commas, whitespace and
192     # optionally the word "and"
193     NICK_LIST = Regexp.new_list(GEN_NICK)
194
195   end
196
197 end
198
199
200 module ::Irc
201
202
203   class BasicUserMessage
204
205     # We extend the BasicUserMessage class with a method that parses a string
206     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
207     # returns an array of channel names, where 'private' or 'pvt' is replaced
208     # by the Symbol :"?", 'here' is replaced by the channel of the message or
209     # by :"?" (depending on whether the message target is the bot or a
210     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
211     #
212     def parse_channel_list(string)
213       return [:*] if [:anywhere, :everywhere].include? string.to_sym
214       string.scan(
215       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
216                  ).map { |chan_ar|
217         chan = chan_ar.first
218         case chan.to_sym
219         when :private, :pvt
220           :"?"
221         when :here
222           case self.target
223           when Channel
224             self.target.name
225           else
226             :"?"
227           end
228         else
229           chan
230         end
231       }.uniq
232     end
233   end
234 end