]> git.cworth.org Git - sup/blob - lib/sup/util.rb
massive fixes for imap and mbox+ssh
[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 with x; yield x; x; end
46 end
47
48 class String
49   def camel_to_hyphy
50     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
51   end
52
53   def find_all_positions x
54     ret = []
55     start = 0
56     while start < length
57       pos = index x, start
58       break if pos.nil?
59       ret << pos
60       start = pos + 1
61     end
62     ret
63   end
64
65   def ucfirst
66     self[0 .. 0].upcase + self[1 .. -1]
67   end
68
69   ## a very complicated regex found on teh internets to split on
70   ## commas, unless they occurr within double quotes.
71   def split_on_commas
72     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
73   end
74
75   def wrap len
76     ret = []
77     s = self
78     while s.length > len
79       cut = s[0 ... len].rindex(/\s/)
80       if cut
81         ret << s[0 ... cut]
82         s = s[(cut + 1) .. -1]
83       else
84         ret << s[0 ... len]
85         s = s[len .. -1]
86       end
87     end
88     ret << s
89   end
90
91   def normalize_whitespace
92     gsub(/\t/, "    ").gsub(/\r/, "")
93   end
94 end
95
96 class Numeric
97   def clamp min, max
98     if self < min
99       min
100     elsif self > max
101       max
102     else
103       self
104     end
105   end
106
107   def in? range; range.member? self; end
108 end
109
110 class Fixnum
111   def num_digits base=10
112     return 1 if self == 0
113     1 + (Math.log(self) / Math.log(10)).floor
114   end
115   
116   def to_character
117     if self < 128 && self >= 0
118       chr
119     else
120       "<#{self}>"
121     end
122   end
123 end
124
125 class Hash
126   def - o
127     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
128   end
129
130   def select_by_value v=true
131     select { |k, vv| vv == v }.map { |x| x.first }
132   end
133 end
134
135 module Enumerable
136   def map_with_index
137     ret = []
138     each_with_index { |x, i| ret << yield(x, i) }
139     ret
140   end
141
142   def sum; inject(0) { |x, y| x + y }; end
143   
144   def map_to_hash
145     ret = {}
146     each { |x| ret[x] = yield(x) }
147     ret
148   end
149
150   # like find, except returns the value of the block rather than the
151   # element itself.
152   def argfind
153     ret = nil
154     find { |e| ret ||= yield(e) }
155     ret || nil # force
156   end
157
158   def argmin
159     best, bestval = nil, nil
160     each do |e|
161       val = yield e
162       if bestval.nil? || val < bestval
163         best, bestval = e, val
164       end
165     end
166     best
167   end
168 end
169
170 class Array
171   def flatten_one_level
172     inject([]) { |a, e| a + e }
173   end
174
175   def to_h; Hash[*flatten]; end
176   def rest; self[1..-1]; end
177
178   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
179   
180   ## apparently uniq doesn't use ==. wtf.
181   def remove_successive_dupes
182     ret = []
183     last = nil
184     each do |e|
185       unless e == last
186         ret << e
187         last = e
188       end
189     end
190     ret
191   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], # heh heh
228         ["month", 12],
229         ["year", nil],
230       ].argfind do |unit, size|
231         if diff <= 1
232           "one #{unit}"
233         elsif size.nil? || diff < size
234           "#{diff} #{unit}s"
235         else
236           diff = (diff / size.to_f).round
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