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
66 def add_file_attachment fn
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.to_s.inspect}"
72 a.header.add "Content-Type", "#{t.content_type}; name=#{bfn.to_s.inspect}"
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"
83 raise EncodingUnsupportedError, t.encoding
90 if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/
98 ## only valid for integer ranges (unless I guess it's exclusive)
100 last - first + (exclude_end? ? 0 : 1)
105 def bool_reader *args
106 args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
108 def bool_writer *args; attr_writer(*args); end
109 def bool_accessor *args
114 def defer_all_other_method_calls_to obj
116 def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
117 def respond_to? meth; @#{obj}.respond_to?(meth); end
127 until klass == Object
129 klass = klass.superclass
135 def returning x; yield x; x; end
137 ## clone of java-style whole-method synchronization
138 ## assumes a @mutex variable
139 ## TODO: clean up, try harder to avoid namespace collisions
140 def synchronized *meth
143 alias unsynchronized_#{meth} #{meth}
145 @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
151 def ignore_concurrent_calls *meth
153 mutex = "@__concurrent_protector_#{meth}"
154 flag = "@__concurrent_flag_#{meth}"
155 oldmeth = "__unprotected_#{meth}"
157 alias #{oldmeth} #{meth}
159 #{mutex} = Mutex.new unless defined? #{mutex}
160 #{flag} = true unless defined? #{flag}
161 run = #{mutex}.synchronize do
168 ret = #{oldmeth}(*a, &b)
169 #{mutex}.synchronize { #{flag} = true }
180 self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
183 def find_all_positions x
195 ## one of the few things i miss from perl
197 self[0 .. 0].upcase + self[1 .. -1]
200 ## a very complicated regex found on teh internets to split on
201 ## commas, unless they occurr within double quotes.
203 split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
206 ## ok, here we do it the hard way. got to have a remainder for purposes of
207 ## tab-completing full email addresses
208 def split_on_commas_with_remainder
215 when :escaped_instring, :escaped_outstring: pos
216 else index(/[,"\\]/, pos)
229 when :outstring: :instring
230 when :instring: :outstring
231 when :escaped_instring: :instring
232 when :escaped_outstring: :outstring
236 when :outstring, :escaped_outstring:
237 ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
238 region_start = newpos + 1
240 when :instring: :instring
241 when :escaped_instring: :instring
245 when :instring: :escaped_instring
246 when :outstring: :escaped_outstring
247 when :escaped_instring: :instring
248 when :escaped_outstring: :outstring
254 remainder = case state
256 self[region_start .. -1].gsub(/^\s+/, "")
268 cut = s[0 ... len].rindex(/\s/)
271 s = s[(cut + 1) .. -1]
280 def normalize_whitespace
281 gsub(/\t/, " ").gsub(/\r/, "")
296 def in? range; range.member? self; end
300 def num_digits base=10
301 return 1 if self == 0
302 1 + (Math.log(self) / Math.log(10)).floor
306 if self < 128 && self >= 0
314 to_s + " " + (self == 1 ? s : s + "s")
320 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
323 def select_by_value v=true
324 select { |k, vv| vv == v }.map { |x| x.first }
331 each_with_index { |x, i| ret << yield(x, i) }
335 def sum; inject(0) { |x, y| x + y }; end
339 each { |x| ret[x] = yield(x) }
343 # like find, except returns the value of the block rather than the
347 find { |e| ret ||= yield(e) }
352 best, bestval = nil, nil
355 if bestval.nil? || val < bestval
356 best, bestval = e, val
362 ## returns the maximum shared prefix of an array of strings
363 ## optinally excluding a prefix
364 def shared_prefix caseless=false, exclude=""
367 (0 ... first.length).each do |i|
368 c = (caseless ? first.downcase : first)[i]
369 break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
370 next if exclude[i] == c
371 prefix += first[i].chr
377 map { |e| yield e }.max
382 def flatten_one_level
383 inject([]) { |a, e| a + e }
386 def to_h; Hash[*flatten]; end
387 def rest; self[1..-1]; end
389 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
391 def last= e; self[-1] = e end
396 sprintf "%012d", self
403 self + (60 - min) * 60
407 def midnight # within a second
408 self - (hour * 60 * 60) - (min * 60) - sec
411 def is_the_same_day? other
412 (midnight - other.midnight).abs < 1
415 def is_the_day_before? other
416 other.midnight - midnight <= 24 * 60 * 60 + 1
419 def to_nice_distance_s from=Time.now
420 later_than = (self < from)
421 diff = (self.to_i - from.to_i).abs.to_f
427 ["week", 4.345], # heh heh
430 ].argfind do |unit, size|
433 elsif size.nil? || diff.round < size
434 "#{diff.round} #{unit}s"
447 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
448 def to_nice_s from=Time.now
451 elsif month != from.month
454 if is_the_same_day? from
456 elsif is_the_day_before? from
457 "Yest." + nearest_hour.strftime("%l%P")
465 ## simple singleton module. far less complete and insane than the ruby
466 ## standard library one, but automatically forwards methods calls and
467 ## allows for constructors that take arguments.
469 ## You must have #initialize call "self.class.i_am_the_instance self"
470 ## at some point or everything will fail horribly.
473 def instance; @instance; end
474 def instantiated?; defined?(@instance) && !@instance.nil?; end
475 def deinstantiate!; @instance = nil; end
476 def method_missing meth, *a, &b
477 raise "no instance defined!" unless defined? @instance
479 ## if we've been deinstantiated, just drop all calls. this is
480 ## useful because threads that might be active during the
481 ## cleanup process (e.g. polling) would otherwise have to
482 ## special-case every call to a Singleton object
483 return nil if @instance.nil?
485 @instance.send meth, *a, &b
487 def i_am_the_instance o
488 raise "there can be only one! (instance)" if defined? @instance
493 def self.included klass
494 klass.extend ClassMethods
498 ## wraps an object. if it throws an exception, keeps a copy, and
499 ## rethrows it for any further method calls.
506 def clear_error!; @e = nil; end
507 def has_errors?; !@e.nil?; end
510 def method_missing m, *a, &b; __pass m, *a, &b; end
512 def id; __pass :id; end
513 def to_s; __pass :to_s; end
514 def to_yaml x; __pass :to_yaml, x; end
515 def is_a? c; @o.is_a? c; end
517 def respond_to? m; @o.respond_to? m end
522 rescue Exception => e
529 ## acts like a hash with an initialization block, but saves any
530 ## newly-created value even upon lookup.
535 ## attr_accessor :val
536 ## def initialize; @val = 0 end
539 ## h = Hash.new { C.new }
544 ## h2 = SavingHash.new { C.new }
549 ## important note: you REALLY want to use #member? to test existence,
550 ## because just checking h[anything] will always evaluate to true
551 ## (except for degenerate constructor blocks that return nil or false)
559 @hash[k] ||= @constructor.call(k)
562 defer_all_other_method_calls_to :hash