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