facets 4.0.0 → 4.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.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CONTRIBUTING.md +18 -2
  3. data/HISTORY.md +205 -0
  4. data/README.md +8 -2
  5. data/lib/core/facets/array/split.rb +16 -9
  6. data/lib/core/facets/class/descendants.rb +21 -8
  7. data/lib/core/facets/enumerable/defer.rb +4 -1
  8. data/lib/core/facets/enumerable/graph.rb +1 -1
  9. data/lib/core/facets/enumerable/map_by.rb +6 -2
  10. data/lib/core/facets/hash/count.rb +19 -8
  11. data/lib/core/facets/hash/deep_merge.rb +25 -20
  12. data/lib/core/facets/integer/ordinal.rb +18 -13
  13. data/lib/core/facets/kernel/blank.rb +9 -4
  14. data/lib/core/facets/kernel/deep_clone.rb +36 -8
  15. data/lib/core/facets/kernel/extend.rb +20 -4
  16. data/lib/core/facets/module/alias_class_method.rb +8 -3
  17. data/lib/core/facets/module/module_def.rb +0 -11
  18. data/lib/core/facets/module/redefine_method.rb +12 -3
  19. data/lib/core/facets/range/overlap.rb +32 -1
  20. data/lib/core/facets/string/indent.rb +32 -20
  21. data/lib/core/facets/string/remove.rb +13 -8
  22. data/lib/core/facets/string/squish.rb +5 -3
  23. data/lib/core/facets/string.rb +1 -0
  24. data/lib/core/facets/time/change.rb +50 -28
  25. data/lib/core/facets/time/future.rb +6 -2
  26. data/lib/core/facets/time/round_to.rb +1 -1
  27. data/lib/core/facets/time/to_time.rb +3 -7
  28. data/lib/core/facets/version.rb +1 -1
  29. data/lib/standard/facets/cloneable.rb +4 -3
  30. data/lib/standard/facets/digest/salted_digest.rb +6 -2
  31. data/lib/standard/facets/fileutils/ln_r.rb +7 -56
  32. data/lib/standard/facets/find/select.rb +3 -1
  33. data/lib/standard/facets/interval.rb +1 -1
  34. data/lib/standard/facets/math/percentile.rb +9 -4
  35. data/lib/standard/facets/ostruct/initialize.rb +7 -6
  36. data/lib/standard/facets/ostruct.rb +3 -3
  37. data/lib/standard/facets/pathname/glob.rb +11 -7
  38. data/lib/standard/facets/shellwords.rb +59 -15
  39. data/lib/standard/facets/zlib.rb +5 -9
  40. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: af1581fdee797dd22551c3257c73b76e2d0e5ee659ecb60690eee877672a5a00
4
- data.tar.gz: 8693eedfa8dc78cfa8c47964cac6f2834996337dc00bbf0e9672c2b664bc2cea
3
+ metadata.gz: c0b8832c335f2a91e27795701f042906df5e734a3e95875f9d5eff91d32a4fff
4
+ data.tar.gz: 4eb0cd3ab5f12aea90d875d04ec996e52c14fd139fcbe456bdd76ab3b3dae368
5
5
  SHA512:
6
- metadata.gz: e4a41b846c6bf81d6103ec0fcac3f8b729f5ab324676ab7f2b25a4126bfe878ec36a7113d58b4a7c32c5d1748cd4a1a9ae4ebba80fa82e7226c83bc7d7220af1
7
- data.tar.gz: 5c32bd85bdeb4336d5774689023e73d5c7e74ee86eff5003e5ef4da1644f10c6de5c897b6a0f268f09c7976055b28acaba10cf420b546380ae21c4d73508da86
6
+ metadata.gz: d2d8dddda82cd3fc70359c563bd39235fcd7876e3a1698a9c5d0b47ee79661cadbe713237297b437fb298e0fbe2ebb94ba0700d8f489d0e96396143a807fceab
7
+ data.tar.gz: 6f1551cbae0a3b0235352c749640ea5861f1946166d76d08c86c8473d909e4e54697a4ca0ee7dea252651a1b5b24e7bdcb565a5235964f7befc887d5349f03fc
data/CONTRIBUTING.md CHANGED
@@ -27,6 +27,16 @@
27
27
  require line, and comment out their line in the aggregator file with
28
28
  `# uncommon`.
29
29
 
30
+ * Facets must not change what Ruby's own methods do, in the core or the
31
+ standard library. A Facets method with the same name as one of Ruby's is
32
+ allowed only if it is compatible, giving Ruby's result for everything
33
+ Ruby's version accepts (or differing only where Ruby's gives no useful
34
+ answer, such as raising or returning nil), and it adds something useful.
35
+ Otherwise Facets gets out of Ruby's way, and the Facets version is either
36
+ dropped or kept under a new name. Never redefine a method just to copy
37
+ Ruby's. If Ruby later adds a method Facets already has, the same rule
38
+ applies.
39
+
30
40
  * Standard libraries that are not extensions of existing standard libraries
31
41
  do not have to be divvied up into individual method files. But note that
32
42
  full classes and/or modules are less likely to make it into Facets, as
@@ -104,8 +114,8 @@ explanation if needed, including *when* and *why* the method could be useful.
104
114
 
105
115
  The test suite uses four tools:
106
116
 
107
- * **RubyTest** provides the test runner interface; `rubytest-cli` supplies the
108
- `ruby-test` command used by the Rake tasks.
117
+ * **RubyTest** provides the test runner interface and the `rubytest` command
118
+ used by the Rake tasks.
109
119
  * **Lemon** defines the `test_case`, `method`, and `test` structure of the unit
110
120
  tests.
111
121
  * **AE** provides assertions such as `.assert` and `expect`, used in both the
@@ -130,6 +140,12 @@ TESTS=test/core/array/test_average.rb bundle exec rake test
130
140
  The Rakefile also provides `test:core`, `test:standard`, `test:rails` and the
131
141
  corresponding `qed:*` tasks for each library area.
132
142
 
143
+ Tests and demos of deprecated methods call them on purpose, so both suites hide
144
+ those deprecation warnings and print a count at the end instead
145
+ (`etc/quiet_deprecations.rb`). A deprecation warning raised from inside `lib/`
146
+ still shows, because it means Facets calls a deprecated method itself. To see
147
+ every warning, set `FACETS_DEPRECATIONS=show`.
148
+
133
149
  * A core method in `lib/core/facets/{class}/{method}.rb` normally has a Lemon
134
150
  test in `test/core/{class}/test_{method}.rb` and a QED demo in
135
151
  `demo/core/{class}/{method}.md`. Standard and rails libraries use
data/HISTORY.md CHANGED
@@ -1,5 +1,210 @@
1
1
  # Facets Release History
2
2
 
3
+ ## 4.1.0 / 2026-11-08
4
+
5
+ Facets and ActiveSupport define many of the same methods, and whichever
6
+ loads last replaces the other's. This release makes a set of those methods
7
+ behave the same in both libraries, so it no longer matters which one wins.
8
+ Facets now matches ActiveSupport 8.1 in these cases, which fixes bugs in
9
+ Rails apps that load Facets, and adds the extra options ActiveSupport's
10
+ versions take.
11
+
12
+ It also stops Facets from changing what Ruby's own methods do. Under a new
13
+ rule, now in CONTRIBUTING.md, a Facets method may share a name with one of
14
+ Ruby's only if it gives Ruby's results and adds something useful. Otherwise
15
+ Facets gets out of Ruby's way.
16
+
17
+ Changes:
18
+
19
+ * Bug Fixes
20
+
21
+ * `Hash#count`, loaded by `require 'facets'`, gives Ruby's own answers
22
+ again. Facets' version counted values rather than key-value pairs, which
23
+ changed Ruby's answer for every library in the program:
24
+ `{a: 1}.count([:a, 1])` returned 0. To count values, use
25
+ `hash.values.count(value)`. Until 2027-09-30, `Hash#count` warns when
26
+ given an argument that can't be a key-value pair, which is how Facets'
27
+ version was called.
28
+ * `Array#shelljoin` from `facets/shellwords` is Ruby's own again. Facets'
29
+ version flattened nested arrays and turned hashes into options, so a
30
+ value meant as one argument could become several. A web request's
31
+ parameter can be an array (`?term[]=&term[]=/home`), and with it
32
+ `['grep', '-r', '--', term, 'public/'].shelljoin` gave
33
+ `grep -r -- '' /home public/`, which prints every file under `/home`.
34
+ Ruby's escapes each element as one argument. To turn hashes into
35
+ options, use `array.shellwords.shelljoin`. Until 2027-09-30,
36
+ `Array#shelljoin` warns when the array has a hash or an array in it.
37
+ * `Hash#shellwords`, and so `Hash#shelljoin` and `Array#shellwords`, no
38
+ longer put quote characters around values. Once the words were escaped
39
+ with `shelljoin`, the quotes became part of the value:
40
+ `{name: 'jim'}.shelljoin` passed `"jim"`, quotes included. Each flag and
41
+ its value is now one plain word, `--name=jim`.
42
+ * `require 'facets'` loads `String#trim`. When `String#margin` was renamed
43
+ to `#trim` in 3.0, the new file was never added to the core aggregator,
44
+ so `trim` worked only with its own require.
45
+ * `Enumerable#defer` with a block works again. Since 3.2 deprecated it,
46
+ `defer` ignored its block, so
47
+ `(1..10).defer { |out, i| out << i if i.even? }.first(5)` returned
48
+ `[1, 2, 3, 4, 5]` instead of `[2, 4, 6, 8, 10]`. It is still
49
+ deprecated; the block form is `Enumerator::Lazy.new(enum) { ... }`.
50
+ * `Range#overlap?` on Ruby 3.1 and 3.2, where Ruby has no version of its
51
+ own, gives the same answers as Ruby's. Facets' version said an empty
52
+ range like `3...3` overlapped any range containing 3, raised RangeError
53
+ for `(3..).overlap?(..5)`, and raised NoMethodError rather than
54
+ TypeError for a non-Range argument. It now follows Ruby's algorithm.
55
+ * `Time.current` uses ActiveSupport's `Time.zone` when it is set. Before,
56
+ when Facets loaded after ActiveSupport, `Time.current` ignored the Rails
57
+ app's time zone and returned the system's local time.
58
+ * `Time#change` keeps the time's UTC offset or time zone. Before, a time
59
+ such as `15:30 +09:00` changed to the system's local time zone. It also
60
+ keeps fractions of a microsecond.
61
+ * Facets' deprecated `Time#to_time`, used only when `date` isn't loaded,
62
+ returns `self`, as Ruby's own does. Before, it converted to local time.
63
+ * `String#blank?` and `String#squish` treat Unicode whitespace, such as a
64
+ non-breaking space, as whitespace. `String#blank?` also works for strings
65
+ in encodings such as UTF-16.
66
+ * `Class#descendants` no longer raises `ArgumentError` when ActiveSupport
67
+ is loaded. Calling it with a number of generations still does, because
68
+ ActiveSupport wraps the method in one that takes no argument.
69
+ * `Integer#ordinal` and `#ordinalize` give `"-1st"` for -1, not `"-1th"`.
70
+ * `String#unindent` with no argument removes only the least indented
71
+ line's indentation from each line. Before, it removed more from the more
72
+ indented lines, so its own example, `"ohaie\n wurld"`, came out as
73
+ `"ohaie\nwurld"`. It also raised `NoMethodError` for an empty string.
74
+ * `String#indent` with a negative number and an indent string of more than
75
+ one character removes only whole copies of that string.
76
+ * `require 'facets/fileutils/ln_r'` replaced Ruby's `FileUtils.link_entry`
77
+ and an internal method it uses with old copies, so Ruby's own
78
+ `FileUtils.cp_lr` raised `NameError`. `FileUtils.ln_r` now uses Ruby's
79
+ `link_entry`, and the file requires `fileutils` itself.
80
+ * `Pathname#glob` from `facets/pathname/glob` ignored a block; it now gives
81
+ the block each match, as Ruby's does. With symbol flags, such as
82
+ `:dotmatch`, it now uses Ruby's glob too, so it works in a directory
83
+ whose name has glob characters such as `[`, and returns paths in the
84
+ same form as it does without them. The file requires `pathname` itself.
85
+ * `Kernel#extend` with no arguments and no block raises `ArgumentError`,
86
+ as Ruby's does; before, it returned the object. `ruby -w` no longer warns
87
+ that `extend` was redefined.
88
+ * `require 'facets/digest'` raised `LoadError`, because it required a file
89
+ that had moved. `#salted_digest`'s automatic salt now comes from
90
+ `SecureRandom` instead of `rand`.
91
+ * `facets/zlib` no longer defines its own copies of Ruby's `Zlib.inflate`
92
+ and `Zlib.deflate`. It now requires `zlib` and `stringio` itself;
93
+ before, `Zlib.compress` raised `NameError` unless they were already
94
+ loaded.
95
+ * `OpenStruct#initialize` from `facets/ostruct` calls Ruby's own
96
+ `initialize` for the hash, instead of a copy of it, and `ruby -w` no
97
+ longer warns that it was redefined.
98
+
99
+ * Additions
100
+
101
+ * `Time#change` takes `nsec:` and `offset:`.
102
+ * `String#remove` and `#remove!` take several patterns.
103
+ * `Hash#deep_merge` and `#deep_merge!` take a block, as `Hash#merge` does,
104
+ to decide the value of a key both hashes have.
105
+ * `Array#split` takes a block instead of a pattern, and splits on `nil`
106
+ when given neither.
107
+ * `String#indent` and `#indent!` take a third argument; when true, empty
108
+ lines are indented too.
109
+
110
+ * Deprecations
111
+
112
+ * `Kernel#extend` with a block, which Facets has added since 2.8.0, now
113
+ warns, and will be removed after 2027-09-30. It's the only reason Facets
114
+ overrides Ruby's `extend`, which every `extend` call in a program then
115
+ goes through. Use `obj.extend(Module.new { ... })` instead. Without
116
+ Facets, Ruby raises if given only a block, and ignores a block given
117
+ with modules.
118
+
119
+ * Changes that can affect existing code
120
+
121
+ * `Hash#count(value)` and `Array#shelljoin` no longer do what Facets'
122
+ versions did; see Bug Fixes. Both warn until 2027-09-30 when called
123
+ the old way.
124
+ * `Hash#shellwords` gives `--name=jim` rather than `--name="jim"`. Code
125
+ that joined the words with spaces into a shell command should use
126
+ `shelljoin` instead.
127
+ * `Array#split` keeps an empty piece where a match is at either end:
128
+ `[2, 1, 2].split(2)` is `[[], [1], []]`, and `[].split(2)` is `[[]]`.
129
+ Before, empty pieces at the end were dropped.
130
+ * `String#indent` leaves empty lines unchanged unless asked. Without an
131
+ indent string, it indents with the string's own indentation character,
132
+ so a tab-indented string gets more tabs.
133
+ * `String#remove!` returns the string even when nothing was removed.
134
+ Before, it returned `nil` then.
135
+ * `Hash#deep_merge!` replaces a sub-hash with a merged copy instead of
136
+ changing it, so other references to the sub-hash no longer see the
137
+ change.
138
+ * `Class#descendants` lists all subclasses before their own descendants.
139
+ On Ruby 4.1, which adds its own `Module#descendants`, a call without a
140
+ number of generations is passed to Ruby's, so it gives Ruby's list, in
141
+ Ruby's order. Only `descendants(n)` is still Facets' own there.
142
+
143
+ ## 4.0.1 / 2026-11-02
144
+
145
+ A patch release with a security fix: `require 'facets/shellwords'` replaced
146
+ Ruby's `Shellwords.escape` with a version that left shell metacharacters
147
+ unescaped. It also lets Rails apps that load Facets boot again, and fixes
148
+ several methods that broke on Ruby 3.
149
+
150
+ Changes:
151
+
152
+ * Bug Fixes
153
+
154
+ * Security: `require 'facets/shellwords'` replaced Ruby's
155
+ `Shellwords.escape`, and with it `String#shellescape`, with a fallback
156
+ that escaped almost nothing. `Shellwords.escape("x; rm -rf ~")` came back
157
+ unchanged, so code that relied on it to quote shell arguments was open to
158
+ command injection. The fallback was meant to apply only where Ruby had no
159
+ `escape`, but its check never matched Ruby's definition, so it always
160
+ applied. It is gone, and Ruby's own `escape` is always used. The bug dates
161
+ back to 2010. `require 'facets'` does not load this file (#67).
162
+ * `require 'facets'` no longer makes `attr`, `attr_reader`, `attr_writer`,
163
+ `attr_accessor`, `remove_method` and `undef_method` protected; Ruby has
164
+ made them public since 2.5. `Module#redefine_method` is now public, like
165
+ ActiveSupport's, so Rails apps that load Facets no longer fail with
166
+ "private method 'redefine_method' called" (#292). A redefined method now
167
+ keeps its visibility; before, a redefined private method became public.
168
+ * `Enumerable#graph` (also `Hash#graph` and `#mash`) and `Interval#step`
169
+ without a block, and every call to `Find.select`, no longer raise
170
+ `ArgumentError` on Ruby 3 (#246). `facets/find/select` now also requires
171
+ `find` itself.
172
+ * `Math.percentile` returns the minimum or maximum at the extremes, as the
173
+ NIST method it cites specifies. `percentile([1,2,3], 90)` raised
174
+ `NoMethodError`, `percentile([1,2,3], 100)` returned `nil` and
175
+ `percentile([1,2,3], 0)` returned 3 (#289).
176
+ * `Kernel#deep_clone` now copies array elements and hash values at any
177
+ depth; before, it only copied instance variables (#11). Equal but distinct
178
+ objects, such as two equal strings, no longer share one copy. Hash keys,
179
+ and Struct and Set members, are still shared with the original.
180
+ * `Enumerable#map_by` maps `false` and `nil` values instead of storing the
181
+ whole element (#75).
182
+ * `Module#alias_class_method` works. It raised `NameError` on every call.
183
+ * `Time#round_to` no longer prints a deprecation warning. It called the
184
+ deprecated `Time#trunc`.
185
+ * The `facets/cloneable` deprecation warning recommends `Kernel#deep_clone`
186
+ or `initialize_copy` instead of `deep_dup`, which Facets doesn't define.
187
+ The 3.2.0 notes gave the same wrong advice.
188
+
189
+ * Documentation
190
+
191
+ * The README names the current release (it still said 3.2.2) and shows how
192
+ to load chosen extensions from a Gemfile with `require: [...]` (#280).
193
+ * The `Shellwords.alt_escape` docs no longer suggest it for `system()`. It
194
+ leaves `$ ; * ? ~` and newlines unescaped, so it is not safe for untrusted
195
+ input.
196
+
197
+ * Internal
198
+
199
+ * The tests use rubytest 0.9's own `rubytest` command instead of the
200
+ `rubytest-cli` gem.
201
+ * The test and demo runs hide the deprecation warnings they trigger on
202
+ purpose and print a count instead. A deprecation warning raised from
203
+ inside `lib/` still shows. Set `FACETS_DEPRECATIONS=show` to see every
204
+ warning.
205
+ * First tests for `Interval#step`, `Find.select` and
206
+ `Module#alias_class_method`.
207
+
3
208
  ## 4.0.0 / 2026-09-27
4
209
 
5
210
  A major release, because it changes behavior: `Kernel#try!` is now the
data/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  **More of Ruby, one method at a time.** Facets is a collection of extensions to Ruby's core classes and standard library, plus a few small, reusable classes and modules. Most methods live in their own files, so you can load one extension, a class's extensions, or the core collection.
7
7
 
8
- Facets took its name in 2004, growing out of a small methods library started in 2002, and is still maintained. The current release is **3.2.2**, which requires **Ruby 3.1 or newer**. See the [release history](HISTORY.md) for changes and migration notes from earlier versions. The `main` branch also contains changes awaiting the next release.
8
+ Facets took its name in 2004, growing out of a small methods library started in 2002, and is still maintained. The current release is **4.1.0**, which requires **Ruby 3.1 or newer**. See the [release history](HISTORY.md) for changes and migration notes from earlier versions. The `main` branch also contains changes awaiting the next release.
9
9
 
10
10
  ## Install
11
11
 
@@ -21,6 +21,12 @@ gem 'facets', require: false
21
21
 
22
22
  `require: false` lets you choose which extensions to load. Omit it if you want Bundler to load the core collection automatically.
23
23
 
24
+ To have Bundler load only certain extensions, for example in a Rails app, list their files instead:
25
+
26
+ ```ruby
27
+ gem 'facets', require: ['facets/array/to_ranges', 'facets/string/snakecase']
28
+ ```
29
+
24
30
  ## Choose how much to load
25
31
 
26
32
  ### One method
@@ -56,7 +62,7 @@ require 'facets'
56
62
  require 'facets/ostruct'
57
63
  ```
58
64
 
59
- This loads `ostruct` and Facets' OpenStruct extensions. On Ruby 3.5+, declare the `ostruct` gem separately because it is no longer a default gem.
65
+ This loads `ostruct` and Facets' OpenStruct extensions. On Ruby 4.0+, list the `ostruct` gem in your Gemfile, because it is now a bundled gem rather than a default gem.
60
66
 
61
67
  ## Documentation
62
68
 
@@ -1,20 +1,30 @@
1
1
  class Array
2
2
 
3
- # Split on matching pattern. Unlike #divide this does not include matching
4
- # elements.
5
- #
6
- # Examples
3
+ # Split on matching elements. Unlike #divide this does not include the
4
+ # matching elements. An element matches if `pattern === element`, so a
5
+ # pattern can be a value, a Regexp or a class.
7
6
  #
8
7
  # ['a1','a2','b1','a3','b2','a4'].split(/^b/)
9
8
  # #=> [['a1','a2'],['a3'],['a4']]
10
9
  #
10
+ # Or give a block, and split where it returns true.
11
+ #
12
+ # [1, 2, 3, 4, 5].split { |x| x % 3 == 0 }
13
+ # #=> [[1, 2], [4, 5]]
14
+ #
15
+ # As with ActiveSupport's Array#split, every match ends a piece, so a match
16
+ # at either end gives an empty piece there.
17
+ #
18
+ # [2, 1, 2].split(2) #=> [[], [1], []]
19
+ # [].split(2) #=> [[]]
20
+ #
11
21
  # Returns list of split-up arrays. [Array<Array>]
12
22
 
13
- def split(pattern)
23
+ def split(pattern=nil, &block)
14
24
  memo = []
15
25
  sect = []
16
26
  each do |obj|
17
- if pattern === obj
27
+ if block ? block.call(obj) : pattern === obj
18
28
  memo << sect
19
29
  sect = []
20
30
  else
@@ -22,9 +32,6 @@ class Array
22
32
  end
23
33
  end
24
34
  memo << sect
25
- memo.pop while memo.last == []
26
- memo
27
35
  end
28
36
 
29
37
  end
30
-
@@ -16,19 +16,32 @@ class Class
16
16
  # X.descendants #=> [Y,Z]
17
17
  # X.descendants(1) #=> [Y]
18
18
  #
19
+ # Ruby 4.1 adds its own Module#descendants. Where Ruby has it, a call
20
+ # without a limit is passed to Ruby's, and Facets only handles the
21
+ # generations limit. Ruby doesn't define the order of its list.
22
+ #
23
+ # On older Rubies, the list is in the same order as ActiveSupport's
24
+ # Class#descendants: the subclasses first, then each one's own
25
+ # descendants.
26
+ #
27
+ # The generations walk goes through #subclasses only, never #descendants,
28
+ # because ActiveSupport wraps #descendants in a version that takes no
29
+ # argument.
30
+ #
31
+ # NOTE: With ActiveSupport loaded, calling descendants with an argument
32
+ # raises ArgumentError, because of that wrapper.
33
+ #
19
34
  # NOTE: This is a intensive operation. Do not expect it to be very fast.
20
35
  #
21
36
  # @author Roger Pack
22
37
  def descendants(generations=-1)
23
- descendants = []
24
- subclasses.each do |k|
25
- descendants << k
26
- if generations != 1
27
- descendants.concat(k.descendants(generations - 1))
28
- end
38
+ return super() if generations < 1 && Module.method_defined?(:descendants)
39
+ walk = lambda do |klass, gen|
40
+ subs = klass.subclasses
41
+ next subs if gen == 1
42
+ subs + subs.flat_map { |k| walk.(k, gen - 1) }
29
43
  end
30
- descendants
44
+ walk.(self, generations)
31
45
  end
32
46
 
33
47
  end
34
-
@@ -26,9 +26,12 @@ module Enumerable
26
26
  # Array or Hash built with the results, or each{...} if you just want
27
27
  # to output each result and discard it.
28
28
  #
29
+ # @deprecated Use Enumerable#lazy, built into Ruby since 2.0. The block
30
+ # form is Enumerator::Lazy.new(enum) { |out, i| ... }. Scheduled for
31
+ # removal after 2027-09-30.
29
32
  def defer(&blk)
30
33
  warn "Enumerable#defer is deprecated. Use Enumerable#lazy instead. It will be removed after 2027-09-30.", uplevel: 1
31
- lazy
34
+ blk ? Enumerator::Lazy.new(self, &blk) : lazy
32
35
  end
33
36
 
34
37
  end
@@ -26,7 +26,7 @@ module Enumerable
26
26
  end
27
27
  h
28
28
  else
29
- Enumerator.new(self,:graph)
29
+ to_enum(:graph)
30
30
  end
31
31
  end
32
32
 
@@ -21,10 +21,14 @@ module Enumerable
21
21
  def map_by #:yield:
22
22
  res = {}
23
23
  each do |a|
24
- k,v = yield(*a)
25
- if v
24
+ r = yield(*a)
25
+ # Test whether a second value was returned, not whether it is truthy,
26
+ # so false and nil are mapped too.
27
+ if Array === r && r.size > 1
28
+ k, v = r
26
29
  (res[k] ||= []) << v
27
30
  else
31
+ k, = r
28
32
  (res[k] ||= []) << a
29
33
  end
30
34
  end
@@ -1,16 +1,27 @@
1
1
  class Hash
2
2
 
3
- # Like Enumerable#count, but can count hash values.
3
+ # Ruby's own Hash#count, from Enumerable, counts key-value pairs:
4
4
  #
5
- # {:A=>1, :B=>1}.count(1) #=> 2
5
+ # {:A=>1, :B=>1}.count([:A, 1]) #=> 1
6
6
  #
7
- def count(*value)
8
- if value.empty?
9
- super()
10
- else
11
- values.count(*value)
7
+ # Facets' version used to count values instead, which changed Ruby's
8
+ # answer for every library in the program. It now returns Ruby's answer,
9
+ # and warns when given something that can't be a key-value pair, since
10
+ # that's how the old Facets version was called. To count values, use
11
+ # `hash.values.count(value)`.
12
+ #
13
+ # {:A=>1, :B=>1}.values.count(1) #=> 2
14
+ #
15
+ # @deprecated Facets no longer changes Hash#count. This warning wrapper is
16
+ # scheduled for removal after 2027-09-30.
17
+ #
18
+ def count(*args, &block)
19
+ if args.size == 1 && !(Array === args.first && args.first.size == 2)
20
+ warn "Facets' Hash#count(value) is deprecated. Hash#count now counts key-value pairs, " \
21
+ "as Ruby's own does, so this returns 0. To count values, use hash.values.count(value). " \
22
+ "It will be removed after 2027-09-30.", uplevel: 1
12
23
  end
24
+ super
13
25
  end
14
26
 
15
27
  end
16
-
@@ -1,33 +1,38 @@
1
1
  class Hash
2
2
 
3
3
  # Same as Hash#merge but recursively merges sub-hashes.
4
+ #
5
+ # {a: {b: 1, c: 2}}.deep_merge(a: {b: 3}) #=> {a: {b: 3, c: 2}}
6
+ #
7
+ # Like Hash#merge, it takes a block to decide the value of a key both
8
+ # hashes have, other than one that is itself merged.
9
+ #
10
+ # {a: {b: 1}}.deep_merge(a: {b: 2}) { |key, mine, theirs| mine + theirs }
11
+ # #=> {a: {b: 3}}
12
+ #
13
+ # A sub-hash is merged only when the other value is a hash too. This
14
+ # matches ActiveSupport's Hash#deep_merge, so the two agree whichever is
15
+ # loaded, and it honors ActiveSupport's #deep_merge? when that's defined.
4
16
 
5
- def deep_merge(other)
6
- hash = self.dup
7
- other.each do |key, value|
8
- myval = self[key]
9
- if value.is_a?(Hash) && myval.is_a?(Hash)
10
- hash[key] = myval.deep_merge(value)
11
- else
12
- hash[key] = value
13
- end
14
- end
15
- hash
17
+ def deep_merge(other, &block)
18
+ dup.deep_merge!(other, &block)
16
19
  end
17
20
 
18
- # Same as Hash#merge! but recursively merges sub-hashes.
21
+ # Same as Hash#merge! but recursively merges sub-hashes. The sub-hashes
22
+ # themselves aren't changed; merged copies replace them.
19
23
 
20
- def deep_merge!(other)
21
- other.each do |key, value|
22
- myval = self[key]
23
- if value.is_a?(Hash) && myval.is_a?(Hash)
24
- myval.deep_merge!(value)
24
+ def deep_merge!(other, &block)
25
+ merge!(other) do |key, mine, theirs|
26
+ deep = Hash === mine &&
27
+ (mine.respond_to?(:deep_merge?) ? mine.deep_merge?(theirs) : Hash === theirs)
28
+ if deep
29
+ mine.deep_merge(theirs, &block)
30
+ elsif block
31
+ block.call(key, mine, theirs)
25
32
  else
26
- self[key] = value
33
+ theirs
27
34
  end
28
35
  end
29
- self
30
36
  end
31
37
 
32
38
  end
33
-
@@ -1,24 +1,29 @@
1
1
  class Integer
2
2
 
3
+ # The number with its English ordinal suffix.
4
+ #
5
+ # 1.ordinal #=> "1st"
6
+ # 12.ordinal #=> "12th"
7
+ # 103.ordinal #=> "103rd"
8
+ # -1.ordinal #=> "-1st"
9
+ #
3
10
  def ordinal
4
- if [11,12,13].include?(self % 100)
5
- "#{self}th"
6
- else
7
- case (self % 10)
8
- when 1
9
- "#{self}st"
10
- when 2
11
- "#{self}nd"
12
- when 3
13
- "#{self}rd"
11
+ n = abs % 100
12
+ suffix =
13
+ if (11..13).include?(n)
14
+ 'th'
14
15
  else
15
- "#{self}th"
16
+ case n % 10
17
+ when 1 then 'st'
18
+ when 2 then 'nd'
19
+ when 3 then 'rd'
20
+ else 'th'
21
+ end
16
22
  end
17
- end
23
+ "#{self}#{suffix}"
18
24
  end
19
25
 
20
26
  # Rails term.
21
27
  alias_method :ordinalize, :ordinal
22
28
 
23
29
  end
24
-
@@ -67,12 +67,17 @@ class Hash
67
67
  end
68
68
 
69
69
  class String
70
- # Is this string just whitespace?
70
+ # Is this string empty or just whitespace? Unicode whitespace, such as a
71
+ # non-breaking space, counts too, as it does in ActiveSupport.
71
72
  #
72
- # "abc".blank? #=> false
73
- # " ".blank? #=> true
73
+ # "abc".blank? #=> false
74
+ # " ".blank? #=> true
75
+ # " ".blank? #=> true
74
76
  def blank?
75
- /\S/ !~ self
77
+ empty? || /\A[[:space:]]*\z/.match?(self)
78
+ rescue Encoding::CompatibilityError
79
+ # e.g. UTF-16 text, which a UTF-8 regexp can't match
80
+ Regexp.new('\A[[:space:]]*\z'.encode(encoding), Regexp::FIXEDENCODING).match?(self)
76
81
  end
77
82
  end
78
83
 
@@ -1,24 +1,52 @@
1
1
  module Kernel
2
2
 
3
3
  # Deep clone an object by deep cloning every instance
4
- # variable as well.
4
+ # variable as well, along with the elements of an Array and
5
+ # the values of a Hash.
6
+ #
7
+ # a = [1, [2, [3]]]
8
+ # b = a.deep_clone
9
+ # b[1][1] << 4
10
+ # a #=> [1, [2, [3]]]
11
+ #
12
+ # Hash keys are not copied: Ruby already copies and freezes String
13
+ # keys, and a hash compared by identity needs the same key objects.
14
+ # Other containers, such as Struct and Set, share their members with
15
+ # the original.
16
+ #
17
+ # An object that is referenced more than once, including an object
18
+ # that contains itself, is copied once.
5
19
  #
6
20
  # Returns [Object]
7
21
 
8
- def deep_clone(cache={})
22
+ def deep_clone(cache={}.compare_by_identity)
9
23
  return cache[self] if cache.key?(self)
10
24
 
11
- copy = clone()
25
+ collection = (Array === self || Hash === self)
26
+
27
+ # A frozen collection's copy is filled in first, then frozen.
28
+ copy = collection ? clone(freeze: false) : clone
12
29
  cache[self] = copy
13
30
 
14
- copy.instance_variables.each do |var|
15
- val = instance_variable_get(var)
31
+ deep = lambda do |val|
16
32
  begin
17
- val = val.deep_clone(cache)
33
+ val.deep_clone(cache)
18
34
  rescue TypeError
19
- next
35
+ val
36
+ end
37
+ end
38
+
39
+ copy.instance_variables.each do |var|
40
+ copy.instance_variable_set(var, deep[instance_variable_get(var)])
41
+ end
42
+
43
+ if collection
44
+ if Array === copy
45
+ copy.map!(&deep)
46
+ else
47
+ copy.transform_values!(&deep)
20
48
  end
21
- copy.instance_variable_set(var, val)
49
+ copy.freeze if frozen?
22
50
  end
23
51
 
24
52
  return copy