6 ## time for some monkeypatching!
10 'host' => "#{ Socket.gethostname }",
11 'pid' => "#{ Process.pid }",
12 'ppid' => "#{ Process.ppid }",
19 def dump_lock_id lock_id = @lock_id
20 "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
21 lock_id.values_at('host','pid','ppid','time','user', 'pname')
25 h = load_lock_id IO.read(path)
26 h['mtime'] = File.mtime path
30 def touch_yourself; touch path end
38 rescue SystemCallError
46 ctime.strftime("%Y-%m-%d %H:%M")
47 rescue SystemCallError
53 ## more monkeypatching!
55 class EncodingUnsupportedError < StandardError; end
58 def self.make_file_attachment fn
59 bfn = File.basename fn
60 t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
61 make_attachment IO.read(fn), t.content_type, t.encoding, bfn.to_s
65 if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/i
70 def self.make_attachment payload, mime_type, encoding, filename
72 a.header.add "Content-Disposition", "attachment; filename=#{filename.inspect}"
73 a.header.add "Content-Type", "#{mime_type}; name=#{filename.inspect}"
74 a.header.add "Content-Transfer-Encoding", encoding if encoding
79 when "quoted-printable"
81 when "7bit", "8bit", nil
84 raise EncodingUnsupportedError, encoding.inspect
92 ## only valid for integer ranges (unless I guess it's exclusive)
94 last - first + (exclude_end? ? 0 : 1)
100 args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
102 def bool_writer *args; attr_writer(*args); end
103 def bool_accessor *args
108 def defer_all_other_method_calls_to obj
110 def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
111 def respond_to?(m, include_private = false)
112 @#{obj}.respond_to?(m, include_private)
123 until klass == Object
125 klass = klass.superclass
131 def returning x; yield x; x; end
133 ## clone of java-style whole-method synchronization
134 ## assumes a @mutex variable
135 ## TODO: clean up, try harder to avoid namespace collisions
136 def synchronized *meth
139 alias unsynchronized_#{meth} #{meth}
141 @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
147 def ignore_concurrent_calls *meth
149 mutex = "@__concurrent_protector_#{meth}"
150 flag = "@__concurrent_flag_#{meth}"
151 oldmeth = "__unprotected_#{meth}"
153 alias #{oldmeth} #{meth}
155 #{mutex} = Mutex.new unless defined? #{mutex}
156 #{flag} = true unless defined? #{flag}
157 run = #{mutex}.synchronize do
164 ret = #{oldmeth}(*a, &b)
165 #{mutex}.synchronize { #{flag} = true }
175 def display_length; scan(/./u).size end
178 self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
181 def find_all_positions x
193 ## a very complicated regex found on teh internets to split on
194 ## commas, unless they occurr within double quotes.
196 split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
199 ## ok, here we do it the hard way. got to have a remainder for purposes of
200 ## tab-completing full email addresses
201 def split_on_commas_with_remainder
208 when :escaped_instring, :escaped_outstring: pos
209 else index(/[,"\\]/, pos)
222 when :outstring: :instring
223 when :instring: :outstring
224 when :escaped_instring: :instring
225 when :escaped_outstring: :outstring
229 when :outstring, :escaped_outstring:
230 ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
231 region_start = newpos + 1
233 when :instring: :instring
234 when :escaped_instring: :instring
238 when :instring: :escaped_instring
239 when :outstring: :escaped_outstring
240 when :escaped_instring: :instring
241 when :escaped_outstring: :outstring
247 remainder = case state
249 self[region_start .. -1].gsub(/^\s+/, "")
261 cut = s[0 ... len].rindex(/\s/)
264 s = s[(cut + 1) .. -1]
273 def normalize_whitespace
274 gsub(/\t/, " ").gsub(/\r/, "")
277 ## takes a space-separated list of words, and returns an array of symbols.
278 ## typically used in Sup for translating Ferret's representation of a list
279 ## of labels (a string) to an array of label symbols.
280 def symbolistize; split.map { |x| x.intern } end
294 def in? range; range.member? self; end
299 elsif self < (1024 * 1024)
300 (self / 1024).to_s + "k"
301 elsif self < (1024 * 1024 * 1024)
302 (self / 1024 / 1024).to_s + "m"
304 (self / 1024 / 1024 / 1024).to_s + "g"
311 if self < 128 && self >= 0
318 ## hacking the english language
335 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
338 def select_by_value v=true
339 select { |k, vv| vv == v }.map { |x| x.first }
346 each_with_index { |x, i| ret << yield(x, i) }
350 def sum; inject(0) { |x, y| x + y }; end
354 each { |x| ret[x] = yield(x) }
358 # like find, except returns the value of the block rather than the
362 find { |e| ret ||= yield(e) }
367 best, bestval = nil, nil
370 if bestval.nil? || val < bestval
371 best, bestval = e, val
377 ## returns the maximum shared prefix of an array of strings
378 ## optinally excluding a prefix
379 def shared_prefix caseless=false, exclude=""
382 (0 ... first.length).each do |i|
383 c = (caseless ? first.downcase : first)[i]
384 break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
385 next if exclude[i] == c
386 prefix += first[i].chr
392 map { |e| yield e }.max
397 def flatten_one_level
398 inject([]) { |a, e| a + e }
401 def to_h; Hash[*flatten]; end
402 def rest; self[1..-1]; end
404 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
406 def last= e; self[-1] = e end
407 def nonempty?; !empty? end
409 def to_set_of_symbols
410 map { |x| x.is_a?(Symbol) ? x : x.intern }.uniq
416 sprintf "%012d", self
423 self + (60 - min) * 60
427 def midnight # within a second
428 self - (hour * 60 * 60) - (min * 60) - sec
431 def is_the_same_day? other
432 (midnight - other.midnight).abs < 1
435 def is_the_day_before? other
436 other.midnight - midnight <= 24 * 60 * 60 + 1
439 def to_nice_distance_s from=Time.now
440 later_than = (self < from)
441 diff = (self.to_i - from.to_i).abs.to_f
447 ["week", 4.345], # heh heh
450 ].argfind do |unit, size|
453 elsif size.nil? || diff.round < size
454 "#{diff.round} #{unit}s"
467 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
468 def to_nice_s from=Time.now
471 elsif month != from.month
474 if is_the_same_day? from
476 elsif is_the_day_before? from
477 "Yest." + nearest_hour.strftime("%l%P")
485 ## simple singleton module. far less complete and insane than the ruby
486 ## standard library one, but automatically forwards methods calls and
487 ## allows for constructors that take arguments.
489 ## You must have #initialize call "self.class.i_am_the_instance self"
490 ## at some point or everything will fail horribly.
493 def instance; @instance; end
494 def instantiated?; defined?(@instance) && !@instance.nil?; end
495 def deinstantiate!; @instance = nil; end
496 def method_missing meth, *a, &b
497 raise "no instance defined!" unless defined? @instance
499 ## if we've been deinstantiated, just drop all calls. this is
500 ## useful because threads that might be active during the
501 ## cleanup process (e.g. polling) would otherwise have to
502 ## special-case every call to a Singleton object
503 return nil if @instance.nil?
505 @instance.send meth, *a, &b
507 def i_am_the_instance o
508 raise "there can be only one! (instance)" if defined? @instance
513 def self.included klass
514 klass.extend ClassMethods
518 ## wraps an object. if it throws an exception, keeps a copy.
528 def clear_error!; @error = nil; end
529 def has_errors?; !@error.nil?; end
531 def method_missing m, *a, &b; __pass m, *a, &b end
533 def id; __pass :id; end
534 def to_s; __pass :to_s; end
535 def to_yaml x; __pass :to_yaml, x; end
536 def is_a? c; @o.is_a? c; end
538 def respond_to?(m, include_private=false)
539 @o.respond_to?(m, include_private)
545 rescue Exception => e
552 ## acts like a hash with an initialization block, but saves any
553 ## newly-created value even upon lookup.
558 ## attr_accessor :val
559 ## def initialize; @val = 0 end
562 ## h = Hash.new { C.new }
567 ## h2 = SavingHash.new { C.new }
572 ## important note: you REALLY want to use #member? to test existence,
573 ## because just checking h[anything] will always evaluate to true
574 ## (except for degenerate constructor blocks that return nil or false)
582 @hash[k] ||= @constructor.call(k)
585 defer_all_other_method_calls_to :hash
588 class OrderedHash < Hash
589 alias_method :store, :[]=
590 alias_method :each_pair, :each
595 a.each { |k, v| self[k] = v }
599 @keys << key unless member?(key)
603 def values; keys.map { |k| self[k] } end
604 def index key; @keys.index key end
611 def each; @keys.each { |k| yield k, self[k] } end
614 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
615 ## first person to hit the finish line
623 @m.synchronize { !@over && @over = true }
628 def self.easy_decode target, charset, text
629 return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
630 charset = case charset
631 when /UTF[-_ ]?8/i: "utf-8"
632 when /(iso[-_ ])?latin[-_ ]?1$/i: "ISO-8859-1"
633 when /iso[-_ ]?8859[-_ ]?15/i: 'ISO-8859-15'
634 when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i: "utf-7"
640 # Remember - Iconv.open(to, from)!
641 Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]