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