]> git.cworth.org Git - sup/blob - lib/sup/util.rb
fixed drafts bug and now pollmode stays hidden upon poll
[sup] / lib / sup / util.rb
1 class Module
2   def bool_reader *args
3     args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
4   end
5   def bool_writer *args; attr_writer(*args); end
6   def bool_accessor *args
7     bool_reader(*args)
8     bool_writer(*args)
9   end
10
11   def defer_all_other_method_calls_to obj
12     class_eval %{ def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end }
13   end
14 end
15
16 class Object
17   def ancestors
18     ret = []
19     klass = self.class
20
21     until klass == Object
22       ret << klass
23       klass = klass.superclass
24     end
25     ret
26   end
27
28   ## takes a value which it yields and then returns, so that code
29   ## like:
30   ##
31   ## x = expensive_operation
32   ## log "got #{x}"
33   ## x
34   ##
35   ## now becomes:
36   ##
37   ## with(expensive_operation) { |x| log "got #{x}" }
38   ##
39   ## i'm sure there's pithy comment i could make here about the
40   ## superiority of lisp, but fuck lisp.
41   def returning x; yield x; x; end
42
43   ## clone of java-style whole-method synchronization
44   ## assumes a @mutex variable
45   def synchronized *meth
46     meth.each do
47       class_eval <<-EOF
48         alias unsynchronized_#{meth} #{meth}
49         def #{meth}(*a, &b)
50           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
51         end
52       EOF
53     end
54   end
55 end
56
57 class String
58   def camel_to_hyphy
59     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
60   end
61
62   def find_all_positions x
63     ret = []
64     start = 0
65     while start < length
66       pos = index x, start
67       break if pos.nil?
68       ret << pos
69       start = pos + 1
70     end
71     ret
72   end
73
74   def ucfirst
75     self[0 .. 0].upcase + self[1 .. -1]
76   end
77
78   ## a very complicated regex found on teh internets to split on
79   ## commas, unless they occurr within double quotes.
80   def split_on_commas
81     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
82   end
83
84   def wrap len
85     ret = []
86     s = self
87     while s.length > len
88       cut = s[0 ... len].rindex(/\s/)
89       if cut
90         ret << s[0 ... cut]
91         s = s[(cut + 1) .. -1]
92       else
93         ret << s[0 ... len]
94         s = s[len .. -1]
95       end
96     end
97     ret << s
98   end
99
100   def normalize_whitespace
101     gsub(/\t/, "    ").gsub(/\r/, "")
102   end
103 end
104
105 class Numeric
106   def clamp min, max
107     if self < min
108       min
109     elsif self > max
110       max
111     else
112       self
113     end
114   end
115
116   def in? range; range.member? self; end
117 end
118
119 class Fixnum
120   def num_digits base=10
121     return 1 if self == 0
122     1 + (Math.log(self) / Math.log(10)).floor
123   end
124   
125   def to_character
126     if self < 128 && self >= 0
127       chr
128     else
129       "<#{self}>"
130     end
131   end
132 end
133
134 class Hash
135   def - o
136     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
137   end
138
139   def select_by_value v=true
140     select { |k, vv| vv == v }.map { |x| x.first }
141   end
142 end
143
144 module Enumerable
145   def map_with_index
146     ret = []
147     each_with_index { |x, i| ret << yield(x, i) }
148     ret
149   end
150
151   def sum; inject(0) { |x, y| x + y }; end
152   
153   def map_to_hash
154     ret = {}
155     each { |x| ret[x] = yield(x) }
156     ret
157   end
158
159   # like find, except returns the value of the block rather than the
160   # element itself.
161   def argfind
162     ret = nil
163     find { |e| ret ||= yield(e) }
164     ret || nil # force
165   end
166
167   def argmin
168     best, bestval = nil, nil
169     each do |e|
170       val = yield e
171       if bestval.nil? || val < bestval
172         best, bestval = e, val
173       end
174     end
175     best
176   end
177 end
178
179 class Array
180   def flatten_one_level
181     inject([]) { |a, e| a + e }
182   end
183
184   def to_h; Hash[*flatten]; end
185   def rest; self[1..-1]; end
186
187   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
188 end
189
190 class Time
191   def to_indexable_s
192     sprintf "%012d", self
193   end
194
195   def nearest_hour
196     if min < 30
197       self
198     else
199       self + (60 - min) * 60
200     end
201   end
202
203   def midnight # within a second
204     self - (hour * 60 * 60) - (min * 60) - sec
205   end
206
207   def is_the_same_day? other
208     (midnight - other.midnight).abs < 1
209   end
210
211   def is_the_day_before? other
212     other.midnight - midnight <=  24 * 60 * 60 + 1
213   end
214
215   def to_nice_distance_s from=Time.now
216     later_than = (self < from)
217     diff = (self.to_i - from.to_i).abs.to_f
218     text = 
219       [ ["second", 60],
220         ["minute", 60],
221         ["hour", 24],
222         ["day", 7],
223         ["week", 4.345], # heh heh
224         ["month", 12],
225         ["year", nil],
226       ].argfind do |unit, size|
227         if diff.round <= 1
228           "one #{unit}"
229         elsif size.nil? || diff.round < size
230           "#{diff.round} #{unit}s"
231         else
232           diff /= size.to_f
233           false
234         end
235       end
236     if later_than
237       text + " ago"
238     else
239       "in " + text
240     end  
241   end
242
243   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
244   def to_nice_s from=Time.now
245     if year != from.year
246       strftime "%b %Y"
247     elsif month != from.month
248       strftime "%b %e"
249     else
250       if is_the_same_day? from
251         strftime("%l:%M%P")
252       elsif is_the_day_before? from
253         "Yest."  + nearest_hour.strftime("%l%P")
254       else
255         strftime "%b %e"
256       end
257     end
258   end
259 end
260
261 ## simple singleton module. far less complete and insane than the ruby
262 ## standard library one, but automatically forwards methods calls and
263 ## allows for constructors that take arguments.
264 ##
265 ## You must have #initialize call "self.class.i_am_the_instance self"
266 ## at some point or everything will fail horribly.
267 module Singleton
268   module ClassMethods
269     def instance; @instance; end
270     def instantiated?; defined?(@instance) && !@instance.nil?; end
271     def deinstantiate!; @instance = nil; end
272     def method_missing meth, *a, &b
273       raise "no instance defined!" unless defined? @instance
274       @instance.send meth, *a, &b
275     end
276     def i_am_the_instance o
277       raise "there can be only one! (instance)" if defined? @instance
278       @instance = o
279     end
280   end
281
282   def self.included klass
283     klass.extend ClassMethods
284   end
285 end
286
287 ## wraps an object. if it throws an exception, keeps a copy, and
288 ## rethrows it for any further method calls.
289 class Recoverable
290   def initialize o
291     @o = o
292     @e = nil
293   end
294
295   def clear_error!; @e = nil; end
296   def has_errors?; !@e.nil?; end
297   def error; @e; end
298
299   def method_missing m, *a, &b; __pass m, *a, &b; end
300   
301   def id; __pass :id; end
302   def to_s; __pass :to_s; end
303   def to_yaml x; __pass :to_yaml, x; end
304   def is_a? c; @o.is_a? c; end
305
306   def __pass m, *a, &b
307     begin
308       @o.send(m, *a, &b)
309     rescue Exception => e
310       @e = e
311       raise e
312     end
313   end
314 end