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