]> git.cworth.org Git - sup/blob - lib/sup/util.rb
yet again reworked error handling and synchronization
[sup] / lib / sup / util.rb
1 class Module
2   def bool_reader *args
3     args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
4   end
5   def bool_writer *args; attr_writer(*args); end
6   def bool_accessor *args
7     bool_reader(*args)
8     bool_writer(*args)
9   end
10
11   def attr_reader_cloned *args
12     args.each { |sym| class_eval %{ def #{sym}; @#{sym}.clone; end } }
13   end
14
15   def defer_all_other_method_calls_to obj
16     class_eval %{ def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end }
17   end
18 end
19
20 class Object
21   def ancestors
22     ret = []
23     klass = self.class
24
25     until klass == Object
26       ret << klass
27       klass = klass.superclass
28     end
29     ret
30   end
31
32   ## takes a value which it yields and then returns, so that code
33   ## like:
34   ##
35   ## x = expensive_operation
36   ## log "got #{x}"
37   ## x
38   ##
39   ## now becomes:
40   ##
41   ## with(expensive_operation) { |x| log "got #{x}" }
42   ##
43   ## i'm sure there's pithy comment i could make here about the
44   ## superiority of lisp, but fuck lisp.
45   def returning x; yield x; x; end
46
47   ## clone of java-style whole-method synchronization
48   ## assumes a @mutex variable
49   def synchronized *meth
50     meth.each do
51       class_eval <<-EOF
52         alias unsynchronized_#{meth} #{meth}
53         def #{meth}(*a, &b)
54           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
55         end
56       EOF
57     end
58   end
59 end
60
61 class String
62   def camel_to_hyphy
63     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
64   end
65
66   def find_all_positions x
67     ret = []
68     start = 0
69     while start < length
70       pos = index x, start
71       break if pos.nil?
72       ret << pos
73       start = pos + 1
74     end
75     ret
76   end
77
78   def ucfirst
79     self[0 .. 0].upcase + self[1 .. -1]
80   end
81
82   ## a very complicated regex found on teh internets to split on
83   ## commas, unless they occurr within double quotes.
84   def split_on_commas
85     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
86   end
87
88   def wrap len
89     ret = []
90     s = self
91     while s.length > len
92       cut = s[0 ... len].rindex(/\s/)
93       if cut
94         ret << s[0 ... cut]
95         s = s[(cut + 1) .. -1]
96       else
97         ret << s[0 ... len]
98         s = s[len .. -1]
99       end
100     end
101     ret << s
102   end
103
104   def normalize_whitespace
105     gsub(/\t/, "    ").gsub(/\r/, "")
106   end
107 end
108
109 class Numeric
110   def clamp min, max
111     if self < min
112       min
113     elsif self > max
114       max
115     else
116       self
117     end
118   end
119
120   def in? range; range.member? self; end
121 end
122
123 class Fixnum
124   def num_digits base=10
125     return 1 if self == 0
126     1 + (Math.log(self) / Math.log(10)).floor
127   end
128   
129   def to_character
130     if self < 128 && self >= 0
131       chr
132     else
133       "<#{self}>"
134     end
135   end
136 end
137
138 class Hash
139   def - o
140     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
141   end
142
143   def select_by_value v=true
144     select { |k, vv| vv == v }.map { |x| x.first }
145   end
146 end
147
148 module Enumerable
149   def map_with_index
150     ret = []
151     each_with_index { |x, i| ret << yield(x, i) }
152     ret
153   end
154
155   def sum; inject(0) { |x, y| x + y }; end
156   
157   def map_to_hash
158     ret = {}
159     each { |x| ret[x] = yield(x) }
160     ret
161   end
162
163   # like find, except returns the value of the block rather than the
164   # element itself.
165   def argfind
166     ret = nil
167     find { |e| ret ||= yield(e) }
168     ret || nil # force
169   end
170
171   def argmin
172     best, bestval = nil, nil
173     each do |e|
174       val = yield e
175       if bestval.nil? || val < bestval
176         best, bestval = e, val
177       end
178     end
179     best
180   end
181 end
182
183 class Array
184   def flatten_one_level
185     inject([]) { |a, e| a + e }
186   end
187
188   def to_h; Hash[*flatten]; end
189   def rest; self[1..-1]; end
190
191   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
192 end
193
194 class Time
195   def to_indexable_s
196     sprintf "%012d", self
197   end
198
199   def nearest_hour
200     if min < 30
201       self
202     else
203       self + (60 - min) * 60
204     end
205   end
206
207   def midnight # within a second
208     self - (hour * 60 * 60) - (min * 60) - sec
209   end
210
211   def is_the_same_day? other
212     (midnight - other.midnight).abs < 1
213   end
214
215   def is_the_day_before? other
216     other.midnight - midnight <=  24 * 60 * 60 + 1
217   end
218
219   def to_nice_distance_s from=Time.now
220     later_than = (self < from)
221     diff = (self.to_i - from.to_i).abs.to_f
222     text = 
223       [ ["second", 60],
224         ["minute", 60],
225         ["hour", 24],
226         ["day", 7],
227         ["week", 4.345], # heh heh
228         ["month", 12],
229         ["year", nil],
230       ].argfind do |unit, size|
231         if diff.round <= 1
232           "one #{unit}"
233         elsif size.nil? || diff.round < size
234           "#{diff.round} #{unit}s"
235         else
236           diff /= size.to_f
237           false
238         end
239       end
240     if later_than
241       text + " ago"
242     else
243       "in " + text
244     end  
245   end
246
247   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
248   def to_nice_s from=Time.now
249     if year != from.year
250       strftime "%b %Y"
251     elsif month != from.month
252       strftime "%b %e"
253     else
254       if is_the_same_day? from
255         strftime("%l:%M%P")
256       elsif is_the_day_before? from
257         "Yest."  + nearest_hour.strftime("%l%P")
258       else
259         strftime "%b %e"
260       end
261     end
262   end
263 end
264
265 ## simple singleton module. far less complete and insane than the ruby
266 ## standard library one, but automatically forwards methods calls and
267 ## allows for constructors that take arguments.
268 ##
269 ## You must have #initialize call "self.class.i_am_the_instance self"
270 ## at some point or everything will fail horribly
271 module Singleton
272   module ClassMethods
273     def instance; @instance; end
274     def instantiated?; defined?(@instance) && !@instance.nil?; end
275     def method_missing meth, *a, &b
276       raise "no instance defined!" unless defined? @instance
277       @instance.send meth, *a, &b
278     end
279     def i_am_the_instance o
280       raise "there can be only one! (instance)" if defined? @instance
281       @instance = o
282     end
283   end
284
285   def self.included klass
286     klass.extend ClassMethods
287   end
288 end