5 ## time for some monkeypatching!
9 'host' => "#{ Socket.gethostname }",
10 'pid' => "#{ Process.pid }",
11 'ppid' => "#{ Process.ppid }",
18 def dump_lock_id lock_id = @lock_id
19 "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
20 lock_id.values_at('host','pid','ppid','time','user', 'pname')
24 h = load_lock_id IO.read(path)
25 h['mtime'] = File.mtime path
29 def touch_yourself; touch path end
37 rescue SystemCallError
43 elsif s < (1024 * 1024)
45 elsif s < (1024 * 1024 * 1024)
46 (s / 1024 / 1024).to_s + "m"
48 (s / 1024 / 1024 / 1024).to_s + "g"
54 ctime.strftime("%Y-%m-%d %H:%M")
55 rescue SystemCallError
61 ## more monkeypatching!
63 class EncodingUnsupportedError < StandardError; end
67 bfn = File.basename fn
69 t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
71 a.header.add "Content-Disposition", "attachment; filename=#{bfn}"
72 a.header.add "Content-Type", "#{t.content_type}; name=#{bfn}"
73 a.header.add "Content-Transfer-Encoding", t.encoding
77 [IO.read(fn)].pack "m"
78 when "quoted-printable"
79 [IO.read(fn)].pack "M"
81 raise EncodingUnsupportedError, t.encoding
90 ## only valid for integer ranges (unless I guess it's exclusive)
92 last - first + (exclude_end? ? 0 : 1)
98 args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
100 def bool_writer *args; attr_writer(*args); end
101 def bool_accessor *args
106 def defer_all_other_method_calls_to obj
108 def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
109 def respond_to? meth; @#{obj}.respond_to?(meth); end
119 until klass == Object
121 klass = klass.superclass
126 ## takes a value which it yields and then returns, so that code
129 ## x = expensive_operation
135 ## with(expensive_operation) { |x| log "got #{x}" }
137 ## i'm sure there's pithy comment i could make here about the
138 ## superiority of lisp, but fuck lisp.
140 ## addendum: apparently this is a "k combinator". whoda thunk it?
141 def returning x; yield x; x; end
143 ## clone of java-style whole-method synchronization
144 ## assumes a @mutex variable
145 def synchronized *meth
148 alias unsynchronized_#{meth} #{meth}
150 @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
159 self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
162 def find_all_positions x
175 self[0 .. 0].upcase + self[1 .. -1]
178 ## a very complicated regex found on teh internets to split on
179 ## commas, unless they occurr within double quotes.
181 split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
188 cut = s[0 ... len].rindex(/\s/)
191 s = s[(cut + 1) .. -1]
200 def normalize_whitespace
201 gsub(/\t/, " ").gsub(/\r/, "")
216 def in? range; range.member? self; end
220 def num_digits base=10
221 return 1 if self == 0
222 1 + (Math.log(self) / Math.log(10)).floor
226 if self < 128 && self >= 0
236 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
239 def select_by_value v=true
240 select { |k, vv| vv == v }.map { |x| x.first }
247 each_with_index { |x, i| ret << yield(x, i) }
251 def sum; inject(0) { |x, y| x + y }; end
255 each { |x| ret[x] = yield(x) }
259 # like find, except returns the value of the block rather than the
263 find { |e| ret ||= yield(e) }
268 best, bestval = nil, nil
271 if bestval.nil? || val < bestval
272 best, bestval = e, val
278 ## returns the maximum shared prefix of an array of strings
279 ## optinally excluding a prefix
280 def shared_prefix exclude=""
283 (0 ... first.length).each do |i|
285 break unless all? { |s| s[i] == c }
286 next if exclude[i] == c
294 def flatten_one_level
295 inject([]) { |a, e| a + e }
298 def to_h; Hash[*flatten]; end
299 def rest; self[1..-1]; end
301 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
303 def last= e; self[-1] = e end
308 sprintf "%012d", self
315 self + (60 - min) * 60
319 def midnight # within a second
320 self - (hour * 60 * 60) - (min * 60) - sec
323 def is_the_same_day? other
324 (midnight - other.midnight).abs < 1
327 def is_the_day_before? other
328 other.midnight - midnight <= 24 * 60 * 60 + 1
331 def to_nice_distance_s from=Time.now
332 later_than = (self < from)
333 diff = (self.to_i - from.to_i).abs.to_f
339 ["week", 4.345], # heh heh
342 ].argfind do |unit, size|
345 elsif size.nil? || diff.round < size
346 "#{diff.round} #{unit}s"
359 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
360 def to_nice_s from=Time.now
363 elsif month != from.month
366 if is_the_same_day? from
368 elsif is_the_day_before? from
369 "Yest." + nearest_hour.strftime("%l%P")
377 ## simple singleton module. far less complete and insane than the ruby
378 ## standard library one, but automatically forwards methods calls and
379 ## allows for constructors that take arguments.
381 ## You must have #initialize call "self.class.i_am_the_instance self"
382 ## at some point or everything will fail horribly.
385 def instance; @instance; end
386 def instantiated?; defined?(@instance) && !@instance.nil?; end
387 def deinstantiate!; @instance = nil; end
388 def method_missing meth, *a, &b
389 raise "no instance defined!" unless defined? @instance
391 ## if we've been deinstantiated, just drop all calls. this is
392 ## useful because threads that might be active during the
393 ## cleanup process (e.g. polling) would otherwise have to
394 ## special-case every call to a Singleton object
395 return nil if @instance.nil?
397 @instance.send meth, *a, &b
399 def i_am_the_instance o
400 raise "there can be only one! (instance)" if defined? @instance
405 def self.included klass
406 klass.extend ClassMethods
410 ## wraps an object. if it throws an exception, keeps a copy, and
411 ## rethrows it for any further method calls.
418 def clear_error!; @e = nil; end
419 def has_errors?; !@e.nil?; end
422 def method_missing m, *a, &b; __pass m, *a, &b; end
424 def id; __pass :id; end
425 def to_s; __pass :to_s; end
426 def to_yaml x; __pass :to_yaml, x; end
427 def is_a? c; @o.is_a? c; end
429 def respond_to? m; @o.respond_to? m end
434 rescue Exception => e
441 ## acts like a hash with an initialization block, but saves any
442 ## newly-created value even upon lookup.
447 ## attr_accessor :val
448 ## def initialize; @val = 0 end
451 ## h = Hash.new { C.new }
456 ## h2 = SavingHash.new { C.new }
461 ## important note: you REALLY want to use #member? to test existence,
462 ## because just checking h[anything] will always evaluate to true
463 ## (except for degenerate constructor blocks that return nil or false)
471 @hash[k] ||= @constructor.call(k)
474 defer_all_other_method_calls_to :hash