X-Git-Url: https://git.cworth.org/git?a=blobdiff_plain;f=lib%2Fsup%2Futil.rb;h=0e06ecd904d6eeed109f15bd0dc64ebf733c5626;hb=4ab181a0665da2112394e09cb35e7a25b68543d1;hp=f1cab57424fa8d3b30997ff6482a3438307c227f;hpb=ee26ef991ab5489a5d400a9253f91a540f033104;p=sup diff --git a/lib/sup/util.rb b/lib/sup/util.rb index f1cab57..0e06ecd 100644 --- a/lib/sup/util.rb +++ b/lib/sup/util.rb @@ -7,6 +7,14 @@ class Module bool_reader(*args) bool_writer(*args) end + + def attr_reader_cloned *args + args.each { |sym| class_eval %{ def #{sym}; @#{sym}.clone; end } } + end + + def defer_all_other_method_calls_to obj + class_eval %{ def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end } + end end class Object @@ -20,6 +28,21 @@ class Object end ret end + + ## takes a value which it yields and then returns, so that code + ## like: + ## + ## x = expensive_operation + ## log "got #{x}" + ## x + ## + ## now becomes: + ## + ## with(expensive_operation) { |x| log "got #{x}" } + ## + ## i'm sure there's pithy comment i could make here about the + ## superiority of lisp, but fuck lisp. + def returning x; yield x; x; end end class String @@ -43,7 +66,8 @@ class String self[0 .. 0].upcase + self[1 .. -1] end - ## found on teh internets + ## a very complicated regex found on teh internets to split on + ## commas, unless they occurr within double quotes. def split_on_commas split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/) end @@ -54,15 +78,19 @@ class String while s.length > len cut = s[0 ... len].rindex(/\s/) if cut - ret << s[0 ... cut] + "\n" + ret << s[0 ... cut] s = s[(cut + 1) .. -1] else - ret << s[0 ... len] + "\n" + ret << s[0 ... len] s = s[len .. -1] end end ret << s end + + def normalize_whitespace + gsub(/\t/, " ").gsub(/\r/, "") + end end class Numeric @@ -148,19 +176,6 @@ class Array def rest; self[1..-1]; end def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end - - ## apparently uniq doesn't use ==. wtf. - def remove_successive_dupes - ret = [] - last = nil - each do |e| - unless e == last - ret << e - last = e - end - end - ret - end end class Time @@ -196,16 +211,16 @@ class Time ["minute", 60], ["hour", 24], ["day", 7], - ["week", 4], # heh heh + ["week", 4.345], # heh heh ["month", 12], ["year", nil], ].argfind do |unit, size| - if diff <= 1 + if diff.round <= 1 "one #{unit}" - elsif size.nil? || diff < size - "#{diff} #{unit}s" + elsif size.nil? || diff.round < size + "#{diff.round} #{unit}s" else - diff = (diff / size.to_f).round + diff /= size.to_f false end end