]> git.cworth.org Git - sup/blob - lib/sup/util.rb
added String#normalize_whitespace and fixed String#wrap to not insert newlines
[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]
74         s = s[(cut + 1) .. -1]
75       else
76         ret << s[0 ... len]
77         s = s[len .. -1]
78       end
79     end
80     ret << s
81   end
82
83   def normalize_whitespace
84     gsub(/\t/, "    ").gsub(/\r/, "")
85   end
86 end
87
88 class Numeric
89   def clamp min, max
90     if self < min
91       min
92     elsif self > max
93       max
94     else
95       self
96     end
97   end
98
99   def in? range; range.member? self; end
100 end
101
102 class Fixnum
103   def num_digits base=10
104     return 1 if self == 0
105     1 + (Math.log(self) / Math.log(10)).floor
106   end
107   
108   def to_character
109     if self < 128 && self >= 0
110       chr
111     else
112       "<#{self}>"
113     end
114   end
115 end
116
117 class Hash
118   def - o
119     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
120   end
121
122   def select_by_value v=true
123     select { |k, vv| vv == v }.map { |x| x.first }
124   end
125 end
126
127 module Enumerable
128   def map_with_index
129     ret = []
130     each_with_index { |x, i| ret << yield(x, i) }
131     ret
132   end
133
134   def sum; inject(0) { |x, y| x + y }; end
135   
136   def map_to_hash
137     ret = {}
138     each { |x| ret[x] = yield(x) }
139     ret
140   end
141
142   # like find, except returns the value of the block rather than the
143   # element itself.
144   def argfind
145     ret = nil
146     find { |e| ret ||= yield(e) }
147     ret || nil # force
148   end
149
150   def argmin
151     best, bestval = nil, nil
152     each do |e|
153       val = yield e
154       if bestval.nil? || val < bestval
155         best, bestval = e, val
156       end
157     end
158     best
159   end
160 end
161
162 class Array
163   def flatten_one_level
164     inject([]) { |a, e| a + e }
165   end
166
167   def to_h; Hash[*flatten]; end
168   def rest; self[1..-1]; end
169
170   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
171   
172   ## apparently uniq doesn't use ==. wtf.
173   def remove_successive_dupes
174     ret = []
175     last = nil
176     each do |e|
177       unless e == last
178         ret << e
179         last = e
180       end
181     end
182     ret
183   end
184 end
185
186 class Time
187   def to_indexable_s
188     sprintf "%012d", self
189   end
190
191   def nearest_hour
192     if min < 30
193       self
194     else
195       self + (60 - min) * 60
196     end
197   end
198
199   def midnight # within a second
200     self - (hour * 60 * 60) - (min * 60) - sec
201   end
202
203   def is_the_same_day? other
204     (midnight - other.midnight).abs < 1
205   end
206
207   def is_the_day_before? other
208     other.midnight - midnight <=  24 * 60 * 60 + 1
209   end
210
211   def to_nice_distance_s from=Time.now
212     later_than = (self < from)
213     diff = (self.to_i - from.to_i).abs.to_f
214     text = 
215       [ ["second", 60],
216         ["minute", 60],
217         ["hour", 24],
218         ["day", 7],
219         ["week", 4], # heh heh
220         ["month", 12],
221         ["year", nil],
222       ].argfind do |unit, size|
223         if diff <= 1
224           "one #{unit}"
225         elsif size.nil? || diff < size
226           "#{diff} #{unit}s"
227         else
228           diff = (diff / size.to_f).round
229           false
230         end
231       end
232     if later_than
233       text + " ago"
234     else
235       "in " + text
236     end  
237   end
238
239   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
240   def to_nice_s from=Time.now
241     if year != from.year
242       strftime "%b %Y"
243     elsif month != from.month
244       strftime "%b %e"
245     else
246       if is_the_same_day? from
247         strftime("%l:%M%P")
248       elsif is_the_day_before? from
249         "Yest."  + nearest_hour.strftime("%l%P")
250       else
251         strftime "%b %e"
252       end
253     end
254   end
255 end
256
257 ## simple singleton module. far less complete and insane than the ruby
258 ## standard library one, but automatically forwards methods calls and
259 ## allows for constructors that take arguments.
260 ##
261 ## You must have #initialize call "self.class.i_am_the_instance self"
262 ## at some point or everything will fail horribly
263 module Singleton
264   module ClassMethods
265     def instance; @instance; end
266     def instantiated?; defined?(@instance) && !@instance.nil?; end
267     def method_missing meth, *a, &b
268       raise "no instance defined!" unless defined? @instance
269       @instance.send meth, *a, &b
270     end
271     def i_am_the_instance o
272       raise "there can be only one! (instance)" if defined? @instance
273       @instance = o
274     end
275   end
276
277   def self.included klass
278     klass.extend ClassMethods
279   end
280 end