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
31 def touch_yourself; touch path end
39 rescue SystemCallError
47 ctime.strftime("%Y-%m-%d %H:%M")
48 rescue SystemCallError
54 ## more monkeypatching!
56 class EncodingUnsupportedError < StandardError; end
59 def self.make_file_attachment fn
60 bfn = File.basename fn
61 t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
62 make_attachment IO.read(fn), t.content_type, t.encoding, bfn.to_s
66 if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/i
71 def self.make_attachment payload, mime_type, encoding, filename
73 a.header.add "Content-Disposition", "attachment; filename=#{filename.inspect}"
74 a.header.add "Content-Type", "#{mime_type}; name=#{filename.inspect}"
75 a.header.add "Content-Transfer-Encoding", encoding if encoding
80 when "quoted-printable"
82 when "7bit", "8bit", nil
85 raise EncodingUnsupportedError, encoding.inspect
93 ## only valid for integer ranges (unless I guess it's exclusive)
95 last - first + (exclude_end? ? 0 : 1)
100 def bool_reader *args
101 args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
103 def bool_writer *args; attr_writer(*args); end
104 def bool_accessor *args
109 def defer_all_other_method_calls_to obj
111 def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
112 def respond_to?(m, include_private = false)
113 @#{obj}.respond_to?(m, include_private)
124 until klass == Object
126 klass = klass.superclass
132 def returning x; yield x; x; end
134 ## clone of java-style whole-method synchronization
135 ## assumes a @mutex variable
136 ## TODO: clean up, try harder to avoid namespace collisions
137 def synchronized *methods
138 methods.each do |meth|
140 alias unsynchronized_#{meth} #{meth}
142 @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
148 def ignore_concurrent_calls *methods
149 methods.each do |meth|
150 mutex = "@__concurrent_protector_#{meth}"
151 flag = "@__concurrent_flag_#{meth}"
152 oldmeth = "__unprotected_#{meth}"
154 alias #{oldmeth} #{meth}
156 #{mutex} = Mutex.new unless defined? #{mutex}
157 #{flag} = true unless defined? #{flag}
158 run = #{mutex}.synchronize do
165 ret = #{oldmeth}(*a, &b)
166 #{mutex}.synchronize { #{flag} = true }
176 ## nasty multibyte hack for ruby 1.8. if it's utf-8, split into chars using
177 ## the utf8 regex and count those. otherwise, use the byte length.
179 if $encoding == "UTF-8"
187 self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
190 def find_all_positions x
202 ## a very complicated regex found on teh internets to split on
203 ## commas, unless they occurr within double quotes.
205 split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
208 ## ok, here we do it the hard way. got to have a remainder for purposes of
209 ## tab-completing full email addresses
210 def split_on_commas_with_remainder
217 when :escaped_instring, :escaped_outstring then pos
218 else index(/[,"\\]/, pos)
231 when :outstring then :instring
232 when :instring then :outstring
233 when :escaped_instring then :instring
234 when :escaped_outstring then :outstring
238 when :outstring, :escaped_outstring then
239 ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
240 region_start = newpos + 1
242 when :instring then :instring
243 when :escaped_instring then :instring
247 when :instring then :escaped_instring
248 when :outstring then :escaped_outstring
249 when :escaped_instring then :instring
250 when :escaped_outstring then :outstring
256 remainder = case state
258 self[region_start .. -1].gsub(/^\s+/, "")
270 cut = s[0 ... len].rindex(/\s/)
273 s = s[(cut + 1) .. -1]
282 def normalize_whitespace
283 gsub(/\t/, " ").gsub(/\r/, "")
286 unless method_defined? :ord
292 ## takes a list of words, and returns an array of symbols. typically used in
293 ## Sup for translating Ferret's representation of a list of labels (a string)
294 ## to an array of label symbols.
296 ## split_on will be passed to String#split, so you can leave this nil for space.
297 def to_set_of_symbols split_on=nil; Set.new split(split_on).map { |x| x.strip.intern } end
311 def in? range; range.member? self; end
316 elsif self < (1024 * 1024)
317 (self / 1024).to_s + "k"
318 elsif self < (1024 * 1024 * 1024)
319 (self / 1024 / 1024).to_s + "m"
321 (self / 1024 / 1024 / 1024).to_s + "g"
328 if self < 128 && self >= 0
335 ## hacking the english language
352 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
355 def select_by_value v=true
356 select { |k, vv| vv == v }.map { |x| x.first }
363 each_with_index { |x, i| ret << yield(x, i) }
367 def sum; inject(0) { |x, y| x + y }; end
371 each { |x| ret[x] = yield(x) }
375 # like find, except returns the value of the block rather than the
379 find { |e| ret ||= yield(e) }
384 best, bestval = nil, nil
387 if bestval.nil? || val < bestval
388 best, bestval = e, val
394 ## returns the maximum shared prefix of an array of strings
395 ## optinally excluding a prefix
396 def shared_prefix caseless=false, exclude=""
399 (0 ... first.length).each do |i|
400 c = (caseless ? first.downcase : first)[i]
401 break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
402 next if exclude[i] == c
403 prefix += first[i].chr
409 map { |e| yield e }.max
414 def flatten_one_level
415 inject([]) { |a, e| a + e }
418 def to_h; Hash[*flatten]; end
419 def rest; self[1..-1]; end
421 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
423 def last= e; self[-1] = e end
424 def nonempty?; !empty? end
429 sprintf "%012d", self
436 self + (60 - min) * 60
440 def midnight # within a second
441 self - (hour * 60 * 60) - (min * 60) - sec
444 def is_the_same_day? other
445 (midnight - other.midnight).abs < 1
448 def is_the_day_before? other
449 other.midnight - midnight <= 24 * 60 * 60 + 1
452 def to_nice_distance_s from=Time.now
453 later_than = (self < from)
454 diff = (self.to_i - from.to_i).abs.to_f
460 ["week", 4.345], # heh heh
463 ].argfind do |unit, size|
466 elsif size.nil? || diff.round < size
467 "#{diff.round} #{unit}s"
480 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
481 def to_nice_s from=Time.now
484 elsif month != from.month
487 if is_the_same_day? from
489 elsif is_the_day_before? from
490 "Yest." + nearest_hour.strftime("%l%P")
498 ## simple singleton module. far less complete and insane than the ruby standard
499 ## library one, but it automatically forwards methods calls and allows for
500 ## constructors that take arguments.
502 ## classes that inherit this can define initialize. however, you cannot call
503 ## .new on the class. To get the instance of the class, call .instance;
504 ## to create the instance, call init.
507 def instance; @instance; end
508 def instantiated?; defined?(@instance) && !@instance.nil?; end
509 def deinstantiate!; @instance = nil; end
510 def method_missing meth, *a, &b
511 raise "no #{name} instance defined in method call to #{meth}!" unless defined? @instance
513 ## if we've been deinstantiated, just drop all calls. this is
514 ## useful because threads that might be active during the
515 ## cleanup process (e.g. polling) would otherwise have to
516 ## special-case every call to a Singleton object
517 return nil if @instance.nil?
519 @instance.send meth, *a, &b
522 raise "there can be only one! (instance)" if defined? @instance
523 @instance = new(*args)
527 def self.included klass
528 klass.private_class_method :allocate, :new
529 klass.extend ClassMethods
533 ## wraps an object. if it throws an exception, keeps a copy.
543 def clear_error!; @error = nil; end
544 def has_errors?; !@error.nil?; end
546 def method_missing m, *a, &b; __pass m, *a, &b end
548 def id; __pass :id; end
549 def to_s; __pass :to_s; end
550 def to_yaml x; __pass :to_yaml, x; end
551 def is_a? c; @o.is_a? c; end
553 def respond_to?(m, include_private=false)
554 @o.respond_to?(m, include_private)
560 rescue Exception => e
567 ## acts like a hash with an initialization block, but saves any
568 ## newly-created value even upon lookup.
573 ## attr_accessor :val
574 ## def initialize; @val = 0 end
577 ## h = Hash.new { C.new }
582 ## h2 = SavingHash.new { C.new }
587 ## important note: you REALLY want to use #member? to test existence,
588 ## because just checking h[anything] will always evaluate to true
589 ## (except for degenerate constructor blocks that return nil or false)
597 @hash[k] ||= @constructor.call(k)
600 defer_all_other_method_calls_to :hash
603 class OrderedHash < Hash
604 alias_method :store, :[]=
605 alias_method :each_pair, :each
610 a.each { |k, v| self[k] = v }
614 @keys << key unless member?(key)
618 def values; keys.map { |k| self[k] } end
619 def index key; @keys.index key end
626 def each; @keys.each { |k| yield k, self[k] } end
629 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
630 ## first person to hit the finish line
638 @m.synchronize { !@over && @over = true }
643 def self.easy_decode target, charset, text
644 return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
645 charset = case charset
646 when /UTF[-_ ]?8/i then "utf-8"
647 when /(iso[-_ ])?latin[-_ ]?1$/i then "ISO-8859-1"
648 when /iso[-_ ]?8859[-_ ]?15/i then 'ISO-8859-15'
649 when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i then "utf-7"
654 Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
655 rescue Errno::EINVAL, Iconv::InvalidEncoding, Iconv::InvalidCharacter, Iconv::IllegalSequence => e
656 info "couldn't transcode text from #{charset} to #{target} (\"#{text[0 ... 20]}\"...)"