]> git.cworth.org Git - sup/blob - lib/sup/util.rb
fixed label and contact-list modes to be a little better
[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 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 end
180
181 class Time
182   def to_indexable_s
183     sprintf "%012d", self
184   end
185
186   def nearest_hour
187     if min < 30
188       self
189     else
190       self + (60 - min) * 60
191     end
192   end
193
194   def midnight # within a second
195     self - (hour * 60 * 60) - (min * 60) - sec
196   end
197
198   def is_the_same_day? other
199     (midnight - other.midnight).abs < 1
200   end
201
202   def is_the_day_before? other
203     other.midnight - midnight <=  24 * 60 * 60 + 1
204   end
205
206   def to_nice_distance_s from=Time.now
207     later_than = (self < from)
208     diff = (self.to_i - from.to_i).abs.to_f
209     text = 
210       [ ["second", 60],
211         ["minute", 60],
212         ["hour", 24],
213         ["day", 7],
214         ["week", 4.345], # heh heh
215         ["month", 12],
216         ["year", nil],
217       ].argfind do |unit, size|
218         if diff.round <= 1
219           "one #{unit}"
220         elsif size.nil? || diff.round < size
221           "#{diff.round} #{unit}s"
222         else
223           diff /= size.to_f
224           false
225         end
226       end
227     if later_than
228       text + " ago"
229     else
230       "in " + text
231     end  
232   end
233
234   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
235   def to_nice_s from=Time.now
236     if year != from.year
237       strftime "%b %Y"
238     elsif month != from.month
239       strftime "%b %e"
240     else
241       if is_the_same_day? from
242         strftime("%l:%M%P")
243       elsif is_the_day_before? from
244         "Yest."  + nearest_hour.strftime("%l%P")
245       else
246         strftime "%b %e"
247       end
248     end
249   end
250 end
251
252 ## simple singleton module. far less complete and insane than the ruby
253 ## standard library one, but automatically forwards methods calls and
254 ## allows for constructors that take arguments.
255 ##
256 ## You must have #initialize call "self.class.i_am_the_instance self"
257 ## at some point or everything will fail horribly
258 module Singleton
259   module ClassMethods
260     def instance; @instance; end
261     def instantiated?; defined?(@instance) && !@instance.nil?; end
262     def method_missing meth, *a, &b
263       raise "no instance defined!" unless defined? @instance
264       @instance.send meth, *a, &b
265     end
266     def i_am_the_instance o
267       raise "there can be only one! (instance)" if defined? @instance
268       @instance = o
269     end
270   end
271
272   def self.included klass
273     klass.extend ClassMethods
274   end
275 end