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
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 space-separated list of words, and returns an array of symbols.
293 ## typically used in Sup for translating Ferret's representation of a list
294 ## of labels (a string) to an array of label symbols.
295 def symbolistize; split.map { |x| x.intern } end
309 def in? range; range.member? self; end
314 elsif self < (1024 * 1024)
315 (self / 1024).to_s + "k"
316 elsif self < (1024 * 1024 * 1024)
317 (self / 1024 / 1024).to_s + "m"
319 (self / 1024 / 1024 / 1024).to_s + "g"
326 if self < 128 && self >= 0
333 ## hacking the english language
350 Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
353 def select_by_value v=true
354 select { |k, vv| vv == v }.map { |x| x.first }
361 each_with_index { |x, i| ret << yield(x, i) }
365 def sum; inject(0) { |x, y| x + y }; end
369 each { |x| ret[x] = yield(x) }
373 # like find, except returns the value of the block rather than the
377 find { |e| ret ||= yield(e) }
382 best, bestval = nil, nil
385 if bestval.nil? || val < bestval
386 best, bestval = e, val
392 ## returns the maximum shared prefix of an array of strings
393 ## optinally excluding a prefix
394 def shared_prefix caseless=false, exclude=""
397 (0 ... first.length).each do |i|
398 c = (caseless ? first.downcase : first)[i]
399 break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
400 next if exclude[i] == c
401 prefix += first[i].chr
407 map { |e| yield e }.max
412 def flatten_one_level
413 inject([]) { |a, e| a + e }
416 def to_h; Hash[*flatten]; end
417 def rest; self[1..-1]; end
419 def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
421 def last= e; self[-1] = e end
422 def nonempty?; !empty? end
424 def to_set_of_symbols
425 map { |x| x.is_a?(Symbol) ? x : x.intern }.uniq
431 sprintf "%012d", self
438 self + (60 - min) * 60
442 def midnight # within a second
443 self - (hour * 60 * 60) - (min * 60) - sec
446 def is_the_same_day? other
447 (midnight - other.midnight).abs < 1
450 def is_the_day_before? other
451 other.midnight - midnight <= 24 * 60 * 60 + 1
454 def to_nice_distance_s from=Time.now
455 later_than = (self < from)
456 diff = (self.to_i - from.to_i).abs.to_f
462 ["week", 4.345], # heh heh
465 ].argfind do |unit, size|
468 elsif size.nil? || diff.round < size
469 "#{diff.round} #{unit}s"
482 TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
483 def to_nice_s from=Time.now
486 elsif month != from.month
489 if is_the_same_day? from
491 elsif is_the_day_before? from
492 "Yest." + nearest_hour.strftime("%l%P")
500 ## simple singleton module. far less complete and insane than the ruby
501 ## standard library one, but automatically forwards methods calls and
502 ## allows for constructors that take arguments.
504 ## You must have #initialize call "self.class.i_am_the_instance self"
505 ## at some point or everything will fail horribly.
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 instance defined!" 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
522 def i_am_the_instance o
523 raise "there can be only one! (instance)" if defined? @instance
528 def self.included klass
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 Redwood::log "warning: error (#{e.class.name}) decoding text from #{charset} to #{target}: #{text[0 ... 20]}"