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