lib/sup/util.rb in sup-0.0.2 vs lib/sup/util.rb in sup-0.0.3

- old
+ new

@@ -5,10 +5,18 @@ def bool_writer *args; attr_writer(*args); end def bool_accessor *args 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 def ancestors ret = [] @@ -18,10 +26,25 @@ ret << klass klass = klass.superclass 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 def camel_to_hyphy self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase @@ -41,28 +64,33 @@ def ucfirst 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 def wrap len ret = [] s = self 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 def clamp min, max