mh_extensions 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/CHANGELOG.rdoc ADDED
@@ -0,0 +1,2 @@
1
+ = Version 0.1.0
2
+ * Gem existence started
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source "http://rubygems.org"
2
+ gemspec
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 Maciej Mensfeld
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest ADDED
@@ -0,0 +1,19 @@
1
+ CHANGELOG.rdoc
2
+ Gemfile
3
+ MIT-LICENSE
4
+ Manifest
5
+ README.md
6
+ Rakefile
7
+ init.rb
8
+ lib/acts_as_tree.rb
9
+ lib/array.rb
10
+ lib/browser_detector.rb
11
+ lib/date.rb
12
+ lib/hash.rb
13
+ lib/mh_extensions.rb
14
+ lib/rand.rb
15
+ lib/range.rb
16
+ lib/string.rb
17
+ lib/string_ext.rb
18
+ lib/txt_file_handler.rb
19
+ mh_extensions.gemspec
data/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # MH Extensions (Must Have Extensions)
2
+
3
+ ## Install
4
+
5
+ gem install mh_extensions
6
+
7
+ and in your Gemfile:
8
+
9
+ gem 'mh_extensions'
10
+
11
+ ## About
12
+
13
+ Package of usefull ruby basic classes extensions and some other usefull libs. For more details view any of files located in `lib/`
14
+
15
+ ## Note on Patches/Pull Requests
16
+
17
+ * Fork the project.
18
+ * Make your feature addition or bug fix.
19
+ * Add tests for it. This is important so I don't break it in a future version unintentionally.
20
+ * Commit, do not mess with Rakefile, version, or history.
21
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
22
+ * Send me a pull request. Bonus points for topic branches.
23
+
24
+ ## Copyright
25
+
26
+ Copyright (c) 2011 Maciej Mensfeld. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'echoe'
4
+
5
+ Echoe.new('mh_extensions', '0.1.0') do |p|
6
+ p.description = "Package of usefull ruby basic classes (and not only) extensions"
7
+ p.url = "https://github.com/mensfeld/mh_extensions"
8
+ p.author = "Maciej Mensfeld"
9
+ p.email = "maciej@mensfeld.pl"
10
+ p.ignore_pattern = ["tmp/*", "script/*"]
11
+ end
12
+
data/init.rb ADDED
@@ -0,0 +1,2 @@
1
+ require 'mh_extensions'
2
+
@@ -0,0 +1,72 @@
1
+ # Rozszerzenie do activerecord::base i do acts_as_tree ktore umozliwia
2
+ # korzystnaie z paru dodatkowych metod
3
+
4
+ # Wymaga do działania bibliotekli rand.rb
5
+ # http://raa.ruby-lang.org/project/rand/
6
+
7
+ class ActiveRecord::Base
8
+ def has_children?
9
+ !self.children.size.zero?
10
+ end
11
+
12
+ def has_siblings?
13
+ !self.siblings.size.zero?
14
+ end
15
+
16
+ # Return the tree depth
17
+ def depth
18
+ return 0 unless has_children?
19
+ children.inject(0) {|dep,c| dep > c.depth ? dep : c.depth} + 1
20
+ end
21
+
22
+ # Return the tree width
23
+ def width
24
+ return 1 unless has_children?
25
+ children.inject(0) {|sum,c| sum + c.width}
26
+ end
27
+
28
+ # Ile węzłów mamy do roota z miejsca gdzie jesteśmy
29
+ def nodes_to_root
30
+ stop = false
31
+ levels = 0
32
+ parent = self.parent_id
33
+ while !stop
34
+ el = parent ? self.class.find(parent) : nil
35
+ if el
36
+ parent = el.parent_id
37
+ levels += 1
38
+ else
39
+ stop = true
40
+ end
41
+ end
42
+ levels
43
+ end
44
+
45
+ # Sprawdza czy nasz rodzic w ogole istnieje
46
+ def valid_parent?
47
+ self.class.exists?(self.parent_id.to_i)
48
+ end
49
+
50
+ # Znajduje korzeń i zwraca go
51
+ def root
52
+ el = self
53
+ nodes_to_root.times {
54
+ el = self.parent
55
+ }
56
+ el
57
+ end
58
+
59
+ def leaf(random = false)
60
+ unless self.has_children?
61
+ return self
62
+ end
63
+
64
+ children = random ? self.children.shuffle : self.children
65
+
66
+ children.each { |child|
67
+ return child.leaf(random)
68
+ }
69
+ nil
70
+ end
71
+
72
+ end
data/lib/array.rb ADDED
@@ -0,0 +1,23 @@
1
+ # Rozszerzenie klasy Array umożliwiające korzystanie z paginacji za pomocą
2
+ # pluginu Kaminaro
3
+ class Array
4
+ def paginable(page, per_page, total_elements_amount)
5
+ @paginate_page = page
6
+ @paginate_per_page = per_page
7
+ @paginate_total_elements_amount = total_elements_amount
8
+ self.instance_eval <<-EVAL
9
+ def current_page
10
+ @paginate_page.to_i
11
+ end
12
+
13
+ def num_pages
14
+ (@paginate_total_elements_amount/@paginate_per_page).floor.to_i
15
+ end
16
+
17
+ def limit_value
18
+ @paginate_per_page.to_i
19
+ end
20
+
21
+ EVAL
22
+ end
23
+ end
@@ -0,0 +1,89 @@
1
+ # Lib used to determine browser version in Rails app
2
+
3
+ class BrowserDetector
4
+ def initialize(request)
5
+ @browser_data = request
6
+ @user_agent = @browser_data.env['HTTP_USER_AGENT'] ?
7
+ @browser_data.env['HTTP_USER_AGENT'].downcase : ''
8
+ end
9
+
10
+ def name
11
+ agent = @user_agent
12
+ if agent =~ /msie/i; return :ie
13
+ elsif agent =~ /konqueror/i; return :konqueror
14
+ elsif agent =~ /chrome/i; return :chrome
15
+ elsif agent =~ /gecko/i; return :mozilla
16
+ elsif agent =~ /opera/i; return :opera
17
+ elsif agent =~ /applewebkit/i; return :safari
18
+ else; return :else
19
+ end
20
+ end
21
+
22
+ def version
23
+ agent = @user_agent
24
+ begin
25
+
26
+ if agent =~ /msie/i
27
+ agent.split(';').second.split(' ').second
28
+ elsif agent =~ /konqueror/i
29
+ agent.split('konqueror/').second.split(' ').first
30
+ elsif agent =~ /chrome/i
31
+ agent.split('chrome/').second.split(' ').first
32
+ elsif agent =~ /gecko/i
33
+ agent.split('firefox/').second.split(' ').first
34
+ elsif agent =~ /opera/i
35
+ agent.split('opera/').second.split(' ').first
36
+ elsif agent =~ /applewebkit/i
37
+ agent.split('safari/').second.split(' ').first
38
+ else
39
+ "Unknown"
40
+ end
41
+ rescue
42
+ return "Unknown"
43
+ end
44
+ end
45
+
46
+ def main_version
47
+ agent = @user_agent
48
+
49
+ begin
50
+ if agent =~ /msie/i
51
+ agent.split(';').second.split(' ').second.split('.').first.to_i
52
+ elsif agent =~ /konqueror/i
53
+ agent.split('konqueror/').second.split(' ').first.split('.').first.to_i
54
+ elsif agent =~ /chrome/i
55
+ agent.split('chrome/').second.split(' ').first.split('.').first.to_i
56
+ elsif agent =~ /gecko/i
57
+ agent.split('firefox/').second.split(' ').first.split('.').first.to_i
58
+ elsif agent =~ /opera/i
59
+ agent.split('opera/').second.split(' ').first.split('.').first.to_i
60
+ elsif agent =~ /applewebkit/i
61
+ agent.split('safari/').second.split(' ').first.split('.').first.to_i
62
+ else
63
+ "Unknown"
64
+ end
65
+ rescue
66
+ return "Unknown"
67
+ end
68
+ end
69
+
70
+ def is_ie6
71
+ return true if self.name == :ie && self.main_version == 6
72
+ return false
73
+ end
74
+
75
+ def is_ie7
76
+ return true if self.name == :ie && self.main_version == 7
77
+ return false
78
+ end
79
+
80
+ def is_ie8
81
+ return true if self.name == :ie && self.main_version >= 8
82
+ return false
83
+ end
84
+
85
+ def is_old_ie
86
+ true if is_ie6 || is_ie7
87
+ end
88
+
89
+ end
data/lib/date.rb ADDED
@@ -0,0 +1,10 @@
1
+ # To change this template, choose Tools | Templates
2
+ # and open the template in the editor.
3
+
4
+ class Date
5
+ def self.from_scratches(s, name, model = :range)
6
+ return nil if s.nil?
7
+ return nil if s[model].nil?
8
+ self.civil(s[model][:"#{name}(1i)"].to_i,s[model][:"#{name}(2i)"].to_i,s[model][:"#{name}(3i)"].to_i)
9
+ end
10
+ end
data/lib/hash.rb ADDED
@@ -0,0 +1,20 @@
1
+ class Hash
2
+ # Zamienia podany hash na zestaw parametrów do linka ?menu=123&cos=12
3
+ def to_url_params
4
+ elements = []
5
+ keys.size.times do |i|
6
+ elements << "#{CGI::escape(keys[i])}=#{CGI::escape(values[i])}"
7
+ end
8
+ elements.join('&')
9
+ end
10
+
11
+ # Zamienia parametry urla na hash ?menu=123&cos=12 => {:menu => 123, :cos => 12}
12
+ def self.from_url_params(url_params)
13
+ result = {}.with_indifferent_access
14
+ url_params.split('&').each do |element|
15
+ element = element.split('=')
16
+ result[element[0]] = element[1]
17
+ end
18
+ result
19
+ end
20
+ end
@@ -0,0 +1,11 @@
1
+ require "acts_as_tree"
2
+ require "array"
3
+ require "date"
4
+ require "hash"
5
+ require "rand"
6
+ require "range"
7
+ require "string"
8
+ require "string_ext"
9
+ require "browser_detector"
10
+ require "txt_file_handler"
11
+
data/lib/rand.rb ADDED
@@ -0,0 +1,412 @@
1
+ #
2
+ # = rand.rb -- library for picking random elements and shuffling
3
+ #
4
+ # Copyright (C) 2004 Ilmari Heikkinen <mailto:kig@misfiring.net>
5
+ #
6
+ # Documentation:: Christian Neukirchen <mailto:chneukirchen@gmail.com>
7
+ #
8
+
9
+
10
+ module Enumerable
11
+ # Choose and return a random element of the Enumerable.
12
+ # [1, 2, 3, 4].pick #=> 2 (or 1, 3, 4)
13
+ def pick
14
+ entries.pick
15
+ end
16
+
17
+ # Return an array of the elements in random order.
18
+ # [1, 2, 3, 4].shuffle #=> [3, 4, 1, 2]
19
+ def shuffle
20
+ entries.shuffle
21
+ end
22
+
23
+ # Calls _block_ once for each element in _self_ in random order,
24
+ # passing that element as a parameter.
25
+ def each_random(&block)
26
+ shuffle.each(&block)
27
+ end
28
+
29
+ # Invokes _block_ once for each element of _self_ in random order.
30
+ # Creates a new array containing the values returned by the block.
31
+ def map_random(&block)
32
+ shuffle.map(&block)
33
+ end
34
+ end
35
+
36
+
37
+ class Array
38
+ # Choose and return a random element of _self_.
39
+ # [1, 2, 3, 4].pick #=> 2 (or 1, 3, 4)
40
+ def pick
41
+ self[pick_index]
42
+ end
43
+
44
+ # Deletes a random element of _self_, returning that element.
45
+ # a = [1, 2, 3, 4]
46
+ # a.pick #=> 2
47
+ # a #=> [1, 3, 4]
48
+ def pick!
49
+ i = pick_index
50
+ rv = self[i]
51
+ delete_at(i)
52
+ rv
53
+ end
54
+
55
+ # Return the index of an random element of _self_.
56
+ # ["foo", "bar", "baz"].pick_index #=> 1 (or 0, or 2)
57
+ def pick_index
58
+ rand(size)
59
+ end
60
+
61
+ # Destructive pick_index. Delete a random element of _self_ and
62
+ # return its index.
63
+ # a = [11, 22, 33, 44]
64
+ # a.pick_index! #=> 2
65
+ # a #=> [11, 22, 44]
66
+ def pick_index!
67
+ i = pick_index
68
+ delete_at i
69
+ i
70
+ end
71
+
72
+ # Return an array of the elements in random order.
73
+ # [11, 22, 33, 44].shuffle #=> [33, 11, 44, 22]
74
+ def shuffle
75
+ sort_by{rand}
76
+ end
77
+
78
+ # Destructive shuffle. Arrange the elements of _self_ in new order.
79
+ # a = [11, 22, 33, 44]
80
+ # a.shuffle!
81
+ # a #=> [33, 11, 44, 22]
82
+ def shuffle!
83
+ sort!{rand <=> 0.5}
84
+ end
85
+ end
86
+
87
+
88
+ class Hash
89
+ # Choose and return a random key-value pair of _self_.
90
+ # {:one => 1, :two => 2, :three => 3}.pick #=> [:one, 1]
91
+ def pick
92
+ k = keys.pick
93
+ [k, self[k]]
94
+ end
95
+
96
+ # Deletes a random key-value pair of _self_, returning that pair.
97
+ # a = {:one => 1, :two => 2, :three => 3}
98
+ # a.pick #=> [:two, 2]
99
+ # a #=> {:one => 1, :three => 3}
100
+ def pick!
101
+ rv = pick
102
+ delete rv.first
103
+ rv
104
+ end
105
+
106
+ # Return a random key of _self_.
107
+ # {:one => 1, :two => 2, :three => 3}.pick_key #=> :three
108
+ def pick_key
109
+ keys.pick
110
+ end
111
+
112
+ # Return a random value of _self_.
113
+ # {:one => 1, :two => 2, :three => 3}.pick_value #=> 3
114
+ def pick_value
115
+ values.pick
116
+ end
117
+
118
+ # Delete a random key-value pair of _self_ and return the key.
119
+ # a = {:one => 1, :two => 2, :three => 3}
120
+ # a.pick_key! #=> :two
121
+ # a #=> {:one => 1, :three => 3}
122
+ def pick_key!
123
+ pick!.first
124
+ end
125
+
126
+ # Delete a random key-value pair of _self_ and return the value.
127
+ # a = {:one => 1, :two => 2, :three => 3}
128
+ # a.pick_value! #=> 2
129
+ # a #=> {:one => 1, :three => 3}
130
+ def pick_value!
131
+ pick!.last
132
+ end
133
+
134
+ # Return the key-value pairs of _self_ with _keys_ and _values_
135
+ # shuffled independedly.
136
+ # {:one => 1, :two => 2, :three => 3}.shuffle_hash_pairs
137
+ # #=> [[:one, 3], [:two, 1], [:three, 2]]
138
+ def shuffle_hash_pairs
139
+ keys.shuffle.zip(values.shuffle)
140
+ end
141
+
142
+ # Return a copy of _self_ with _values_ arranged in random order.
143
+ # {:one => 1, :two => 2, :three => 3}.shuffle_hash
144
+ # #=> {:two=>2, :three=>1, :one=>3}
145
+ def shuffle_hash
146
+ shuffled = {}
147
+ shuffle_hash_pairs.each{|k, v|
148
+ shuffled[k] = v
149
+ }
150
+ shuffled
151
+ end
152
+
153
+ # Destructive shuffle_hash. Arrange the values of _self_ in
154
+ # new, random order.
155
+ # h = {:one => 1, :two => 2, :three => 3}
156
+ # h.shuffle_hash!
157
+ # h #=> {:two=>2, :three=>1, :one=>3}
158
+ def shuffle_hash!
159
+ shuffle_hash_pairs.each{|k, v|
160
+ self[k] = v
161
+ }
162
+ self
163
+ end
164
+ end
165
+
166
+
167
+ class String
168
+ # Return the string with characters arranged in random order.
169
+ # "Ruby rules".shuffle_chars #=> "e lybRsuur"
170
+ def shuffle_chars
171
+ split(//).shuffle.join('')
172
+ end
173
+
174
+ # Destructive shuffle_chars. Arrange the characters of the string
175
+ # in new, random order.
176
+ # s = "Ruby rules".shuffle_chars
177
+ # s.shuffle_chars!
178
+ # s #=> "e lybRsuur"
179
+ def shuffle_chars!
180
+ self[0,size] = shuffle_chars
181
+ end
182
+
183
+ # Return a random byte of _self_.
184
+ # "Ruby rules".pick_byte #=> 121
185
+ def pick_byte
186
+ self[pick_index]
187
+ end
188
+
189
+ # Return a single-character string of a random character in _self_.
190
+ # "Ruby rules".pick_char #=> "y"
191
+ def pick_char
192
+ pick_byte.chr
193
+ end
194
+
195
+ # Destructive pick_char. Delete a random character of the string
196
+ # and return it as a single-character string.
197
+ # s = "Ruby rules"
198
+ # s.pick_char! #=> "y"
199
+ # s #=> "Rub rules"
200
+ def pick_char!
201
+ i = pick_index
202
+ rv = self[i,1]
203
+ self[i,1] = ""
204
+ rv
205
+ end
206
+
207
+ # Destructive pick_byte. Delete a random byte of _self_ and return it.
208
+ # s = "Ruby rules"
209
+ # s.pick_byte! #=> 121
210
+ # s #=> "Rub rules"
211
+ def pick_byte!
212
+ pick_char![0]
213
+ end
214
+
215
+ # Return a random byte index of _self_.
216
+ # "Ruby rules".pick_index #=> 3
217
+ def pick_index
218
+ rand(size)
219
+ end
220
+
221
+ # Destructive pick_index. Delete a random byte of _self_ and
222
+ # return it's index.
223
+ # s = "Ruby rules"
224
+ # s.pick_index #=> 3
225
+ # s #=> "Rub rules"
226
+ def pick_index!
227
+ i = pick_index
228
+ self[i,1] = ""
229
+ i
230
+ end
231
+ end
232
+
233
+
234
+ if __FILE__ == $0
235
+
236
+ require 'test/unit'
237
+
238
+ module RandTestHelpers # :nodoc:
239
+ def picker(enum, enum_check, method, n=50)
240
+ (1..n).all?{ enum_check.include? enum.send(method) }
241
+ end
242
+
243
+ def try_shuffling(enum, enum_c, method)
244
+ rv = nil
245
+ 10.times{
246
+ rv = enum.send method
247
+ break if rv != enum_c
248
+ }
249
+ rv
250
+ end
251
+ end
252
+
253
+
254
+ class RandArrayTest < Test::Unit::TestCase # :nodoc:
255
+ include RandTestHelpers
256
+
257
+ def ar
258
+ (0..99).to_a
259
+ end
260
+
261
+ def test_pick
262
+ a = ar
263
+ results = (0...a.size).map{ a.pick }
264
+ assert true, results.all? {|r| a.include? r }
265
+ end
266
+
267
+ def test_pick!
268
+ a = ar
269
+ results = (0...a.size).map{ a.pick! }
270
+ assert true, results.sort == (0..99).to_a and a.empty?
271
+ end
272
+
273
+ def test_pick_index
274
+ a = ar
275
+ results = (0...a.size).map{ a.pick_index }
276
+ assert true, results.all? {|r| r.between?(0, a.size-1) }
277
+ end
278
+
279
+ def test_pick_index!
280
+ a = ar
281
+ # side-effect-relying block; a.size = a.size-1 after pick_index!,
282
+ # so the picked index max value is the new a.size
283
+ assert true, (0...a.size).all?{ a.pick_index!.between?(0, a.size) } and a.empty?
284
+ end
285
+
286
+ def test_shuffle
287
+ a = ar
288
+ shuffled = try_shuffling(a, a, :shuffle)
289
+ assert true, shuffled.sort == a and shuffled != a
290
+ end
291
+
292
+ def test_shuffle!
293
+ a = ar
294
+ try_shuffling(a, ar, :shuffle!)
295
+ assert true, a != ar and a.sort == ar
296
+ end
297
+ end
298
+
299
+
300
+ class RandHashTest < Test::Unit::TestCase # :nodoc:
301
+ include RandTestHelpers
302
+
303
+ def ha
304
+ Hash[*(1..100).to_a]
305
+ end
306
+
307
+ def test_pick
308
+ assert true, picker(ha, ha.entries, :pick)
309
+ end
310
+
311
+ def test_pick!
312
+ h = ha
313
+ assert true, picker(h, ha.entries, :pick!) and h.empty?
314
+ end
315
+
316
+ def test_pick_key
317
+ assert true, picker(ha, ha.keys, :pick_key)
318
+ end
319
+
320
+ def test_pick_key!
321
+ h = ha
322
+ assert true, picker(h, ha.keys, :pick_key!) and h.empty?
323
+ end
324
+
325
+ def test_pick_value
326
+ assert true, picker(ha, ha.values, :pick_value)
327
+ end
328
+
329
+ def test_pick_value!
330
+ h = ha
331
+ assert true, picker(h, ha.values, :pick_value!) and h.empty?
332
+ end
333
+
334
+ def test_shuffle_hash
335
+ h = ha
336
+ hs = try_shuffling(ha, h, :shuffle_hash)
337
+ assert true, hs != h and (hs.keys + hs.values).sort == (h.keys + h.values).sort
338
+ end
339
+
340
+ def test_shuffle_hash!
341
+ h = ha
342
+ hs = ha
343
+ try_shuffling(hs, h, :shuffle_hash!)
344
+ assert true, hs != h and (hs.keys + hs.values).sort == (h.keys + h.values).sort
345
+ end
346
+
347
+ def test_shuffle
348
+ h = ha
349
+ hs = try_shuffling(ha, h, :shuffle)
350
+ assert true, hs != h and hs.entries.sort == h.entries.sort
351
+ end
352
+ end
353
+
354
+
355
+ class RandStringTest < Test::Unit::TestCase # :nodoc:
356
+ include RandTestHelpers
357
+
358
+ def self.pick_tests(endings)
359
+ endings.each{|ending, compare_str_f|
360
+ define_method("test_pick#{ending}"){
361
+ s = str
362
+ assert true, picker(s, instance_eval(&compare_str_f), "pick#{ending}", s.size)
363
+ }
364
+ }
365
+ end
366
+
367
+ def self.pick_tests!(endings)
368
+ endings.each{|ending, compare_str_f|
369
+ define_method("test_pick#{ending}!"){
370
+ s = str
371
+ assert true, picker(s, instance_eval(&compare_str_f), "pick#{ending}!", s.size) and s.empty?
372
+ }
373
+ }
374
+ end
375
+
376
+ def str
377
+ (("a".."z").to_s + "\n") * 10
378
+ end
379
+
380
+ def test_shuffle
381
+ s = str
382
+ ss = try_shuffling(s, s.to_a, :shuffle)
383
+ assert true, ss != s.to_a and ss.sort == s.to_a.sort
384
+ end
385
+
386
+ def test_shuffle_chars
387
+ s = str
388
+ ss = try_shuffling(s, s.split(//), :shuffle_chars)
389
+ assert true, ss != s and ss.split(//).sort == s.split(//).sort
390
+ end
391
+
392
+ def test_shuffle_chars!
393
+ s = str
394
+ ss = str
395
+ try_shuffling(ss, s.split(//), :shuffle_chars!)
396
+ assert true, ss != s and ss.split(//).sort == s.split(//).sort
397
+ end
398
+
399
+ pick_tests({ "" => lambda{str.to_a},
400
+ :_char => lambda{str.split(//)},
401
+ :_byte => lambda{str.split(//).map{|c| c[0]}},
402
+ :_index => lambda{(0...str.size).to_a}
403
+ })
404
+
405
+ pick_tests!({ :_char => lambda{str.split(//)},
406
+ :_byte => lambda{str.split(//).map{|c| c[0]}},
407
+ :_index => lambda{(0...str.size).to_a}
408
+ })
409
+ end
410
+
411
+
412
+ end #if
data/lib/range.rb ADDED
@@ -0,0 +1,8 @@
1
+ # Małe rozszerzenie do klasy przedziałów - sprawdza czy przedział podany
2
+ # zawiera sie w naszym
3
+
4
+ class Range
5
+ def overlap?(range)
6
+ self.include?(range.first) || range.include?(self.first)
7
+ end
8
+ end
data/lib/string.rb ADDED
@@ -0,0 +1,90 @@
1
+ # coding: utf-8
2
+ # Dodatkowe metody klasy string
3
+
4
+ class String
5
+
6
+ # Czy cenzurowano a jesli tak to ile niedobrych słów było
7
+ @censored_words = false
8
+
9
+ # Zwraca strina bez polskich literek, z małej litery, z usuniętymi innymi
10
+ # znakami oraz z zamienioną spacją na pauze (-)
11
+ def to_url
12
+ temp = self.downcase
13
+ temp
14
+ temp.gsub!(/[âäàãáäå�?ăąǎǟǡǻ�?ȃȧẵặ]/,'a')
15
+ temp.gsub!(/[ëêéèẽēĕėẻȅȇẹȩęḙḛ�?ếễểḕḗệ�?]/,'e')
16
+ temp.gsub!(/[�?iìíîĩīĭïỉ�?ịįȉȋḭɨḯ]/,'i')
17
+ temp.gsub!(/[òóôõ�?�?ȯö�?őǒ�?�?ơǫ�?ɵøồốỗổȱȫȭ�?�?ṑṓ�?ớỡởợǭộǿ]/,'o')
18
+ temp.gsub!(/[ùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự]/,'u')
19
+ temp.gsub!(/[ỳýŷỹȳ�?ÿỷẙƴỵ]/,'y')
20
+ temp.gsub!(/[ñǹń]/,'n')
21
+ temp.gsub!(/[çć]/,'c')
22
+ temp.gsub!(/[ß]/,'ss')
23
+ temp.gsub!(/[œ]/,'oe')
24
+ temp.gsub!(/[ij]/,'ij')
25
+ temp.gsub!(/[�?ł]/,'l')
26
+ temp.gsub!(/[ś]/,'s')
27
+ temp.gsub!(/[źż]/,'z')
28
+ temp.gsub!(/[^a-zA-Z 0-9]/, "")
29
+ temp.gsub!(/\s/,'-')
30
+ temp.gsub!(/\-+$/,'')
31
+ temp.gsub!(/^\-+/,'')
32
+ temp
33
+ end
34
+
35
+ # to_url tylko wykonane na sobie
36
+ def to_url!
37
+ self.replace self.to_url
38
+ end
39
+
40
+ # Zamienia znak nowej linii na <br>'a
41
+ def nl2br
42
+ self.gsub("\n\r","<br>").gsub("\r", "").gsub("\n", "<br />")
43
+ end
44
+
45
+ def nl2br!
46
+ self.replace self.nl2br
47
+ end
48
+
49
+ # Przycina tekst do lenght znakow dodajac end_str na koncu
50
+ def trim(length = 20, end_str = '...')
51
+ if self.length > length
52
+ return "#{self[0, length-end_str.length]}#{end_str}"
53
+ end
54
+ self
55
+ end
56
+
57
+ # trim tylko wykonane na sobie
58
+ def trim!(length = 20, end_str = '...')
59
+ self.replace self.trim(length, end_str)
60
+ self
61
+ end
62
+
63
+ # Cenzuruje niechciane słowa na podstawie tego co jest w bazie i zwraca
64
+ def censor(changer = '*')
65
+ Censor.run(self, changer)
66
+ end
67
+
68
+ # To samo co wyżej tylko operuje na sobie
69
+ def censor!(changer = '*')
70
+ @censored_words = Censor.amount(self)
71
+ self.replace Censor.run(self, changer)
72
+ end
73
+
74
+ # Czy dany string został ocenzurowany
75
+ def censored?
76
+ @censored_words
77
+ end
78
+
79
+ # Zamiana CamelCase na underline
80
+ def underlinize
81
+ self.split(/(?=[A-Z])/).join('_').downcase
82
+ end
83
+
84
+ # Zamiana CamelCase na underline na sobie
85
+ def underlinize!
86
+ self.replace self.underlinize
87
+ self
88
+ end
89
+
90
+ end
data/lib/string_ext.rb ADDED
@@ -0,0 +1,57 @@
1
+ # coding: utf-8
2
+
3
+ # Required string extensions
4
+
5
+ class String
6
+ # Removes any "not url friendly" stuff and returns "pure" url
7
+ def to_url
8
+ temp = self.downcase
9
+ temp
10
+ temp.gsub!(/[âäàãáäå�?ăąǎǟǡǻ�?ȃȧẵặ]/,'a')
11
+ temp.gsub!(/[ëêéèẽēĕėẻȅȇẹȩęḙḛ�?ếễểḕḗệ�?]/,'e')
12
+ temp.gsub!(/[�?iìíîĩīĭïỉ�?ịįȉȋḭɨḯ]/,'i')
13
+ temp.gsub!(/[òóôõ�?�?ȯö�?őǒ�?�?ơǫ�?ɵøồốỗổȱȫȭ�?�?ṑṓ�?ớỡởợǭộǿ]/,'o')
14
+ temp.gsub!(/[ùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự]/,'u')
15
+ temp.gsub!(/[ỳýŷỹȳ�?ÿỷẙƴỵ]/,'y')
16
+ temp.gsub!(/[ñǹń]/,'n')
17
+ temp.gsub!(/[çć]/,'c')
18
+ temp.gsub!(/[ß]/,'ss')
19
+ temp.gsub!(/[œ]/,'oe')
20
+ temp.gsub!(/[ij]/,'ij')
21
+ temp.gsub!(/[�?ł]/,'l')
22
+ temp.gsub!(/[ś]/,'s')
23
+ temp.gsub!(/[źż]/,'z')
24
+ temp.gsub!(/[^a-zA-Z 0-9]/, "")
25
+ temp.gsub!(/\s/,'-')
26
+ temp.gsub!(/\-+$/,'')
27
+ temp.gsub!(/^\-+/,'')
28
+ temp
29
+ end
30
+
31
+ def to_url!
32
+ self.replace self.to_url
33
+ end
34
+
35
+ # Change new line to html <br/>
36
+ def nl2br
37
+ self.gsub("\n\r","<br>").gsub("\r", "").gsub("\n", "<br />")
38
+ end
39
+
40
+ def nl2br!
41
+ self.replace self.nl2br
42
+ end
43
+
44
+ # Trim string to required length
45
+ def trim(length = 20, end_str = '...')
46
+ if self.length > length
47
+ return "#{self[0, length-end_str.length]}#{end_str}"
48
+ end
49
+ self
50
+ end
51
+
52
+ def trim!(length = 20, end_str = '...')
53
+ self.replace self.trim(length, end_str)
54
+ self
55
+ end
56
+
57
+ end
@@ -0,0 +1,109 @@
1
+ # Lil lib used to read txt files
2
+ class TxtFileHandler
3
+ def initialize(fileadr, relative = true)
4
+ if relative
5
+ @path = File.join(Rails.root, fileadr)
6
+ else
7
+ @path = fileadr
8
+ end
9
+
10
+ end
11
+
12
+ def line(nr)
13
+ return unless ropen
14
+ line = nil
15
+ i = 0
16
+ @file.each_line{ |s|
17
+ if i == nr
18
+ line = s
19
+ close
20
+ break
21
+ end
22
+ i+=1
23
+ }
24
+ return line
25
+ end
26
+
27
+ def line_nr
28
+ return unless ropen
29
+ i = 0
30
+ @file.each_line{ |s|
31
+ i+=1
32
+ }
33
+ close
34
+ i
35
+ end
36
+
37
+ def lines(start, finish)
38
+ return unless ropen
39
+ lines = []
40
+
41
+ if start > finish
42
+ temp = start
43
+ start = finish
44
+ finish = temp
45
+ invert = true
46
+ end
47
+
48
+ i = 0
49
+ j = 0
50
+ @file.each_line{ |s|
51
+ if (i >= start && i <= finish)
52
+ lines[j] = s.gsub("", "Ruby")
53
+ j+=1
54
+ end
55
+ i+=1
56
+ }
57
+ if invert
58
+ lines = lines.reverse
59
+ end
60
+ close
61
+ lines
62
+ end
63
+
64
+ def file
65
+ @file
66
+ end
67
+
68
+ def self.exist?(fileadr, relative = true)
69
+ if relative
70
+ path = File.join(Rails.root, fileadr)
71
+ else
72
+ path = fileadr
73
+ end
74
+ FileTest.exist?(path)
75
+ end
76
+
77
+ def clear!
78
+ close
79
+ return unless wopen
80
+ @file << ""
81
+ close
82
+ end
83
+
84
+ private
85
+
86
+ def ropen
87
+ if TxtFileHandler::exist?(@path, false)
88
+ @file = File.open(@path, "r")
89
+ return true
90
+ end
91
+ return false
92
+ end
93
+
94
+ def wopen
95
+ if TxtFileHandler::exist?(@path, false)
96
+ @file = File.open(@path, "w")
97
+ return true
98
+ end
99
+ return false
100
+ end
101
+
102
+ def close
103
+ if @file
104
+ @file.close
105
+ @file = nil
106
+ end
107
+ end
108
+
109
+ end
@@ -0,0 +1,31 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = %q{mh_extensions}
5
+ s.version = "0.1.0"
6
+
7
+ s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
8
+ s.authors = ["Maciej Mensfeld"]
9
+ s.cert_chain = ["/home/mencio/.cert_keys/gem-public_cert.pem"]
10
+ s.date = %q{2011-04-10}
11
+ s.description = %q{Package of usefull ruby basic classes (and not only) extensions}
12
+ s.email = %q{maciej@mensfeld.pl}
13
+ s.extra_rdoc_files = ["CHANGELOG.rdoc", "README.md", "lib/acts_as_tree.rb", "lib/array.rb", "lib/browser_detector.rb", "lib/date.rb", "lib/hash.rb", "lib/mh_extensions.rb", "lib/rand.rb", "lib/range.rb", "lib/string.rb", "lib/string_ext.rb", "lib/txt_file_handler.rb"]
14
+ s.files = ["CHANGELOG.rdoc", "Gemfile", "MIT-LICENSE", "Manifest", "README.md", "Rakefile", "init.rb", "lib/acts_as_tree.rb", "lib/array.rb", "lib/browser_detector.rb", "lib/date.rb", "lib/hash.rb", "lib/mh_extensions.rb", "lib/rand.rb", "lib/range.rb", "lib/string.rb", "lib/string_ext.rb", "lib/txt_file_handler.rb", "mh_extensions.gemspec"]
15
+ s.homepage = %q{https://github.com/mensfeld/mh_extensions}
16
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Mh_extensions", "--main", "README.md"]
17
+ s.require_paths = ["lib"]
18
+ s.rubyforge_project = %q{mh_extensions}
19
+ s.rubygems_version = %q{1.5.2}
20
+ s.signing_key = %q{/home/mencio/.cert_keys/gem-private_key.pem}
21
+ s.summary = %q{Package of usefull ruby basic classes (and not only) extensions}
22
+
23
+ if s.respond_to? :specification_version then
24
+ s.specification_version = 3
25
+
26
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
27
+ else
28
+ end
29
+ else
30
+ end
31
+ end
data.tar.gz.sig ADDED
Binary file
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mh_extensions
3
+ version: !ruby/object:Gem::Version
4
+ prerelease:
5
+ version: 0.1.0
6
+ platform: ruby
7
+ authors:
8
+ - Maciej Mensfeld
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain:
12
+ - |
13
+ -----BEGIN CERTIFICATE-----
14
+ MIIDMjCCAhqgAwIBAgIBADANBgkqhkiG9w0BAQUFADA/MQ8wDQYDVQQDDAZtYWNp
15
+ ZWoxGDAWBgoJkiaJk/IsZAEZFghtZW5zZmVsZDESMBAGCgmSJomT8ixkARkWAnBs
16
+ MB4XDTExMDQwOTA5NDcyMloXDTEyMDQwODA5NDcyMlowPzEPMA0GA1UEAwwGbWFj
17
+ aWVqMRgwFgYKCZImiZPyLGQBGRYIbWVuc2ZlbGQxEjAQBgoJkiaJk/IsZAEZFgJw
18
+ bDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL0+nG3V4/exIeiJ0IN+
19
+ wVfq8Utcu4Qpo+58EIVMIu3FiK+8w6MBvatZnUrRu12pqWLw9xrUkCiYeRErD+jF
20
+ AmdggIM/tu9CcjvURXH7VeTzOVA+pnV+eJWMD61o8HljFVcb/nyEYYVKErtr9/O4
21
+ QrIGv5lnszq1PMj2sBMy2gOP1YnzawncMLmkpp/T5SU4JZ5gAktGMRVz8RxmZzF5
22
+ 6NVqFLbuqSRSU5U//WJvZVJt8dycCGgQzBM4Vi3nkOWyjIF0BANf1TqnlU2u6s8d
23
+ UK1AoDZfg5feef5e8eqoomHebX1opNGM/SOQhu3LRgax4rJfnl6VS3I2wighohsf
24
+ AgcCAwEAAaM5MDcwCQYDVR0TBAIwADAdBgNVHQ4EFgQUGlrWBqxVieAPk7NEzBDp
25
+ kM+iAMMwCwYDVR0PBAQDAgSwMA0GCSqGSIb3DQEBBQUAA4IBAQAJMoyBaJs8boiz
26
+ lFpbw6MWjk+7ZhqoHpFrWEV4nzb5GzyHZ7GU/pa1fSEQR0SCs+LnTLQbAYNQyUTT
27
+ O+UsTuA7xzI//v6cSodv3Q9NbfoDlou74xv1NXorWoosQFMpVWrXv+c/1RqU3cq4
28
+ WUr+rRiveEXG4tXOwkrpX8KH8xVp2vQZcGw3AXPqhzfqDGzpHd6ws3lk+8HoSrSo
29
+ 2L68tDoxraF2Z2toAg9vfFw1+mOeDk1xVIPVcBy3tJxstHfHGHlQuMiRiDQX2b2D
30
+ YYU8UWVt2841IwB5Dgl4O+atXhe9ZTBO0W32pl4Bq5CP9lhQRT1KL7sxfznJlF7Y
31
+ BH3YFsdk
32
+ -----END CERTIFICATE-----
33
+
34
+ date: 2011-04-10 00:00:00 +02:00
35
+ default_executable:
36
+ dependencies: []
37
+
38
+ description: Package of usefull ruby basic classes (and not only) extensions
39
+ email: maciej@mensfeld.pl
40
+ executables: []
41
+
42
+ extensions: []
43
+
44
+ extra_rdoc_files:
45
+ - CHANGELOG.rdoc
46
+ - README.md
47
+ - lib/acts_as_tree.rb
48
+ - lib/array.rb
49
+ - lib/browser_detector.rb
50
+ - lib/date.rb
51
+ - lib/hash.rb
52
+ - lib/mh_extensions.rb
53
+ - lib/rand.rb
54
+ - lib/range.rb
55
+ - lib/string.rb
56
+ - lib/string_ext.rb
57
+ - lib/txt_file_handler.rb
58
+ files:
59
+ - CHANGELOG.rdoc
60
+ - Gemfile
61
+ - MIT-LICENSE
62
+ - Manifest
63
+ - README.md
64
+ - Rakefile
65
+ - init.rb
66
+ - lib/acts_as_tree.rb
67
+ - lib/array.rb
68
+ - lib/browser_detector.rb
69
+ - lib/date.rb
70
+ - lib/hash.rb
71
+ - lib/mh_extensions.rb
72
+ - lib/rand.rb
73
+ - lib/range.rb
74
+ - lib/string.rb
75
+ - lib/string_ext.rb
76
+ - lib/txt_file_handler.rb
77
+ - mh_extensions.gemspec
78
+ has_rdoc: true
79
+ homepage: https://github.com/mensfeld/mh_extensions
80
+ licenses: []
81
+
82
+ post_install_message:
83
+ rdoc_options:
84
+ - --line-numbers
85
+ - --inline-source
86
+ - --title
87
+ - Mh_extensions
88
+ - --main
89
+ - README.md
90
+ require_paths:
91
+ - lib
92
+ required_ruby_version: !ruby/object:Gem::Requirement
93
+ none: false
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: "0"
98
+ required_rubygems_version: !ruby/object:Gem::Requirement
99
+ none: false
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: "1.2"
104
+ requirements: []
105
+
106
+ rubyforge_project: mh_extensions
107
+ rubygems_version: 1.5.2
108
+ signing_key:
109
+ specification_version: 3
110
+ summary: Package of usefull ruby basic classes (and not only) extensions
111
+ test_files: []
112
+
metadata.gz.sig ADDED
@@ -0,0 +1,2 @@
1
+ L��xô���V�/����6"+ڕ�G��t1=���*��T="ਃW;����q�:~A|j>����jg�t �Yڴ�ȣ��$|��܋�t���ĈR�E<C.p6`�*�l�c���P�4���\ŏT�r�(��S�%�K#6��*Lt���8�n����;�܌�x�1�C3�}���xZ;�l]Z
2
+ ߲6��Cw"z��k��oz��GC��d�=�u�ɨ�