3 ## time for some monkeypatching!
7 'host' => "#{ Socket.gethostname }",
8 'pid' => "#{ Process.pid }",
9 'ppid' => "#{ Process.ppid }",
16 def dump_lock_id lock_id = @lock_id
17 "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
18 lock_id.values_at('host','pid','ppid','time','user', 'pname')
22 h = load_lock_id IO.read(path)
23 h['mtime'] = File.stat(path).mtime
33 ## only valid for integer ranges (unless I guess it's exclusive)
35 last - first + (exclude_end? ? 0 : 1)
41 args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
43 def bool_writer *args; attr_writer(*args); end
44 def bool_accessor *args
49 def defer_all_other_method_calls_to obj
51 def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
52 def respond_to? meth; @#{obj}.respond_to?(meth); end
64 klass = klass.superclass
69 ## takes a value which it yields and then returns, so that code
72 ## x = expensive_operation
78 ## with(expensive_operation) { |x| log "got #{x}" }
80 ## i'm sure there's pithy comment i could make here about the
81 ## superiority of lisp, but fuck lisp.
82 def returning x; yield x; x; end
84 ## clone of java-style whole-method synchronization
85 ## assumes a @mutex variable
86 def synchronized *meth
89 alias unsynchronized_#{meth} #{meth}
91 @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
100 self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
103 def find_all_positions x
116 self[0 .. 0].upcase + self[1 .. -1]
119 ## a very complicated regex found on teh internets to split on
120 ## commas, unless they occurr within double quotes.
122 split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
129 cut = s[0 ... len].rindex(/\s/)
132 s = s[(cut + 1) .. -1]
141 def normalize_whitespace
142 gsub(/\t/, " ").gsub(/\r/, "")
157 def in? range; range.member? self; end
161 def num_digits base=10
162 return 1 if self == 0
163 1 + (Math.log(self) / Math.log(10)).floor
167 if self < 128 && self >= 0
177 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
180 def select_by_value v=true
181 select { |k, vv| vv == v }.map { |x| x.first }
188 each_with_index { |x, i| ret << yield(x, i) }
192 def sum; inject(0) { |x, y| x + y }; end
196 each { |x| ret[x] = yield(x) }
200 # like find, except returns the value of the block rather than the
204 find { |e| ret ||= yield(e) }
209 best, bestval = nil, nil
212 if bestval.nil? || val < bestval
213 best, bestval = e, val
221 def flatten_one_level
222 inject([]) { |a, e| a + e }
225 def to_h; Hash[*flatten]; end
226 def rest; self[1..-1]; end
228 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
233 sprintf "%012d", self
240 self + (60 - min) * 60
244 def midnight # within a second
245 self - (hour * 60 * 60) - (min * 60) - sec
248 def is_the_same_day? other
249 (midnight - other.midnight).abs < 1
252 def is_the_day_before? other
253 other.midnight - midnight <= 24 * 60 * 60 + 1
256 def to_nice_distance_s from=Time.now
257 later_than = (self < from)
258 diff = (self.to_i - from.to_i).abs.to_f
264 ["week", 4.345], # heh heh
267 ].argfind do |unit, size|
270 elsif size.nil? || diff.round < size
271 "#{diff.round} #{unit}s"
284 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
285 def to_nice_s from=Time.now
288 elsif month != from.month
291 if is_the_same_day? from
293 elsif is_the_day_before? from
294 "Yest." + nearest_hour.strftime("%l%P")
302 ## simple singleton module. far less complete and insane than the ruby
303 ## standard library one, but automatically forwards methods calls and
304 ## allows for constructors that take arguments.
306 ## You must have #initialize call "self.class.i_am_the_instance self"
307 ## at some point or everything will fail horribly.
310 def instance; @instance; end
311 def instantiated?; defined?(@instance) && !@instance.nil?; end
312 def deinstantiate!; @instance = nil; end
313 def method_missing meth, *a, &b
314 raise "no instance defined!" unless defined? @instance
315 @instance.send meth, *a, &b
317 def i_am_the_instance o
318 raise "there can be only one! (instance)" if defined? @instance
323 def self.included klass
324 klass.extend ClassMethods
328 ## wraps an object. if it throws an exception, keeps a copy, and
329 ## rethrows it for any further method calls.
336 def clear_error!; @e = nil; end
337 def has_errors?; !@e.nil?; end
340 def method_missing m, *a, &b; __pass m, *a, &b; end
342 def id; __pass :id; end
343 def to_s; __pass :to_s; end
344 def to_yaml x; __pass :to_yaml, x; end
345 def is_a? c; @o.is_a? c; end
347 def respond_to? m; @o.respond_to? m end
352 rescue Exception => e
359 ## acts like a hash with an initialization block, but saves any
360 ## newly-created value even upon lookup.
365 ## attr_accessor :val
366 ## def initialize; @val = 0 end
369 ## h = Hash.new { C.new }
374 ## h2 = SavingHash.new { C.new }
379 ## important note: you REALLY want to use #member? to test existence,
380 ## because just checking h[anything] will always evaluate to true
381 ## (except for degenerate constructor blocks that return nil or false)
389 @hash[k] ||= @constructor.call(k)
392 defer_all_other_method_calls_to :hash