7 ## time for some monkeypatching!
11 'host' => "#{ Socket.gethostname }",
12 'pid' => "#{ Process.pid }",
13 'ppid' => "#{ Process.ppid }",
20 def dump_lock_id lock_id = @lock_id
21 "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
22 lock_id.values_at('host','pid','ppid','time','user', 'pname')
26 h = load_lock_id IO.read(path)
27 h['mtime'] = File.mtime path
32 def touch_yourself; touch path end
40 rescue SystemCallError
48 ctime.strftime("%Y-%m-%d %H:%M")
49 rescue SystemCallError
55 ## more monkeypatching!
57 class EncodingUnsupportedError < StandardError; end
60 def self.make_file_attachment fn
61 bfn = File.basename fn
62 t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
63 make_attachment IO.read(fn), t.content_type, t.encoding, bfn.to_s
67 if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/i
72 def self.make_attachment payload, mime_type, encoding, filename
74 a.header.add "Content-Disposition", "attachment; filename=#{filename.inspect}"
75 a.header.add "Content-Type", "#{mime_type}; name=#{filename.inspect}"
76 a.header.add "Content-Transfer-Encoding", encoding if encoding
81 when "quoted-printable"
83 when "7bit", "8bit", nil
86 raise EncodingUnsupportedError, encoding.inspect
94 ## only valid for integer ranges (unless I guess it's exclusive)
96 last - first + (exclude_end? ? 0 : 1)
101 def bool_reader *args
102 args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
104 def bool_writer *args; attr_writer(*args); end
105 def bool_accessor *args
110 def defer_all_other_method_calls_to obj
112 def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
113 def respond_to?(m, include_private = false)
114 @#{obj}.respond_to?(m, include_private)
125 until klass == Object
127 klass = klass.superclass
133 def returning x; yield x; x; end
135 ## clone of java-style whole-method synchronization
136 ## assumes a @mutex variable
137 ## TODO: clean up, try harder to avoid namespace collisions
138 def synchronized *methods
139 methods.each do |meth|
141 alias unsynchronized_#{meth} #{meth}
143 @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
149 def ignore_concurrent_calls *methods
150 methods.each do |meth|
151 mutex = "@__concurrent_protector_#{meth}"
152 flag = "@__concurrent_flag_#{meth}"
153 oldmeth = "__unprotected_#{meth}"
155 alias #{oldmeth} #{meth}
157 #{mutex} = Mutex.new unless defined? #{mutex}
158 #{flag} = true unless defined? #{flag}
159 run = #{mutex}.synchronize do
166 ret = #{oldmeth}(*a, &b)
167 #{mutex}.synchronize { #{flag} = true }
177 ## nasty multibyte hack for ruby 1.8. if it's utf-8, split into chars using
178 ## the utf8 regex and count those. otherwise, use the byte length.
180 if $encoding == "UTF-8" || $encoding == "utf8"
188 self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
191 def find_all_positions x
203 ## a very complicated regex found on teh internets to split on
204 ## commas, unless they occurr within double quotes.
206 split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
209 ## ok, here we do it the hard way. got to have a remainder for purposes of
210 ## tab-completing full email addresses
211 def split_on_commas_with_remainder
218 when :escaped_instring, :escaped_outstring then pos
219 else index(/[,"\\]/, pos)
232 when :outstring then :instring
233 when :instring then :outstring
234 when :escaped_instring then :instring
235 when :escaped_outstring then :outstring
239 when :outstring, :escaped_outstring then
240 ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
241 region_start = newpos + 1
243 when :instring then :instring
244 when :escaped_instring then :instring
248 when :instring then :escaped_instring
249 when :outstring then :escaped_outstring
250 when :escaped_instring then :instring
251 when :escaped_outstring then :outstring
257 remainder = case state
259 self[region_start .. -1].gsub(/^\s+/, "")
271 cut = s[0 ... len].rindex(/\s/)
274 s = s[(cut + 1) .. -1]
283 def normalize_whitespace
284 gsub(/\t/, " ").gsub(/\r/, "")
287 unless method_defined? :ord
293 ## takes a list of words, and returns an array of symbols. typically used in
294 ## Sup for translating Ferret's representation of a list of labels (a string)
295 ## to an array of label symbols.
297 ## split_on will be passed to String#split, so you can leave this nil for space.
298 def to_set_of_symbols split_on=nil; Set.new split(split_on).map { |x| x.strip.intern } end
312 def in? range; range.member? self; end
317 elsif self < (1024 * 1024)
318 (self / 1024).to_s + "k"
319 elsif self < (1024 * 1024 * 1024)
320 (self / 1024 / 1024).to_s + "m"
322 (self / 1024 / 1024 / 1024).to_s + "g"
329 if self < 128 && self >= 0
336 ## hacking the english language
353 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
356 def select_by_value v=true
357 select { |k, vv| vv == v }.map { |x| x.first }
364 each_with_index { |x, i| ret << yield(x, i) }
368 def sum; inject(0) { |x, y| x + y }; end
372 each { |x| ret[x] = yield(x) }
376 # like find, except returns the value of the block rather than the
380 find { |e| ret ||= yield(e) }
385 best, bestval = nil, nil
388 if bestval.nil? || val < bestval
389 best, bestval = e, val
395 ## returns the maximum shared prefix of an array of strings
396 ## optinally excluding a prefix
397 def shared_prefix caseless=false, exclude=""
400 (0 ... first.length).each do |i|
401 c = (caseless ? first.downcase : first)[i]
402 break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
403 next if exclude[i] == c
404 prefix += first[i].chr
410 map { |e| yield e }.max
415 def flatten_one_level
416 inject([]) { |a, e| a + e }
419 def to_h; Hash[*flatten]; end
420 def rest; self[1..-1]; end
422 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
424 def last= e; self[-1] = e end
425 def nonempty?; !empty? end
430 sprintf "%012d", self
437 self + (60 - min) * 60
441 def midnight # within a second
442 self - (hour * 60 * 60) - (min * 60) - sec
445 def is_the_same_day? other
446 (midnight - other.midnight).abs < 1
449 def is_the_day_before? other
450 other.midnight - midnight <= 24 * 60 * 60 + 1
453 def to_nice_distance_s from=Time.now
454 later_than = (self < from)
455 diff = (self.to_i - from.to_i).abs.to_f
461 ["week", 4.345], # heh heh
464 ].argfind do |unit, size|
467 elsif size.nil? || diff.round < size
468 "#{diff.round} #{unit}s"
481 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
482 def to_nice_s from=Time.now
485 elsif month != from.month
488 if is_the_same_day? from
490 elsif is_the_day_before? from
491 "Yest." + nearest_hour.strftime("%l%P")
499 ## simple singleton module. far less complete and insane than the ruby standard
500 ## library one, but it automatically forwards methods calls and allows for
501 ## constructors that take arguments.
503 ## classes that inherit this can define initialize. however, you cannot call
504 ## .new on the class. To get the instance of the class, call .instance;
505 ## to create the instance, call init.
508 def instance; @instance; end
509 def instantiated?; defined?(@instance) && !@instance.nil?; end
510 def deinstantiate!; @instance = nil; end
511 def method_missing meth, *a, &b
512 raise "no #{name} instance defined in method call to #{meth}!" unless defined? @instance
514 ## if we've been deinstantiated, just drop all calls. this is
515 ## useful because threads that might be active during the
516 ## cleanup process (e.g. polling) would otherwise have to
517 ## special-case every call to a Singleton object
518 return nil if @instance.nil?
520 @instance.send meth, *a, &b
523 raise "there can be only one! (instance)" if defined? @instance
524 @instance = new(*args)
528 def self.included klass
529 klass.private_class_method :allocate, :new
530 klass.extend ClassMethods
534 ## wraps an object. if it throws an exception, keeps a copy.
544 def clear_error!; @error = nil; end
545 def has_errors?; !@error.nil?; end
547 def method_missing m, *a, &b; __pass m, *a, &b end
549 def id; __pass :id; end
550 def to_s; __pass :to_s; end
551 def to_yaml x; __pass :to_yaml, x; end
552 def is_a? c; @o.is_a? c; end
554 def respond_to?(m, include_private=false)
555 @o.respond_to?(m, include_private)
561 rescue Exception => e
568 ## acts like a hash with an initialization block, but saves any
569 ## newly-created value even upon lookup.
574 ## attr_accessor :val
575 ## def initialize; @val = 0 end
578 ## h = Hash.new { C.new }
583 ## h2 = SavingHash.new { C.new }
588 ## important note: you REALLY want to use #member? to test existence,
589 ## because just checking h[anything] will always evaluate to true
590 ## (except for degenerate constructor blocks that return nil or false)
598 @hash[k] ||= @constructor.call(k)
601 defer_all_other_method_calls_to :hash
604 class OrderedHash < Hash
605 alias_method :store, :[]=
606 alias_method :each_pair, :each
611 a.each { |k, v| self[k] = v }
615 @keys << key unless member?(key)
619 def values; keys.map { |k| self[k] } end
620 def index key; @keys.index key end
627 def each; @keys.each { |k| yield k, self[k] } end
630 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
631 ## first person to hit the finish line
639 @m.synchronize { !@over && @over = true }
644 def self.easy_decode target, charset, text
645 return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
646 charset = case charset
647 when /UTF[-_ ]?8/i then "utf-8"
648 when /(iso[-_ ])?latin[-_ ]?1$/i then "ISO-8859-1"
649 when /iso[-_ ]?8859[-_ ]?15/i then 'ISO-8859-15'
650 when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i then "utf-7"
655 Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
656 rescue Errno::EINVAL, Iconv::InvalidEncoding, Iconv::InvalidCharacter, Iconv::IllegalSequence => e
657 warn "couldn't transcode text from #{charset} to #{target} (\"#{text[0 ... 20]}\"...) (got #{e.message}); using original as is"