Skip to content

Commit 33157e2

Browse files
authored
Merge pull request rails#43726 from timoschilling/add-pathname-existence
add Pathname#existence
2 parents df35d93 + a2e9e33 commit 33157e2

File tree

5 files changed

+60
-0
lines changed

5 files changed

+60
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
* Add `Pathname#existence`.
2+
3+
```ruby
4+
Pathname.new("file").existence&.read
5+
```
6+
7+
*Timo Schilling*
8+
19
* Remove deprecate `ActiveSupport::Multibyte::Unicode.default_normalization_form`.
210

311
*Rafael Mendonça França*
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# frozen_string_literal: true
2+
3+
require "active_support/core_ext/pathname/existence"
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# frozen_string_literal: true
2+
3+
class Pathname
4+
# Returns the receiver if the named file exists otherwise returns +nil+.
5+
# <tt>pathname.existence</tt> is equivalent to
6+
#
7+
# pathname.existence? ? object : nil
8+
#
9+
# For example, something like
10+
#
11+
# content = pathname.read if pathname.exist?
12+
#
13+
# becomes
14+
#
15+
# content = pathname.existence&.read
16+
#
17+
# @return [Pathname]
18+
def existence
19+
self if exist?
20+
end
21+
end
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "../../abstract_unit"
4+
require "active_support/core_ext/pathname/existence"
5+
6+
class PathnameExistenceTest < ActiveSupport::TestCase
7+
def test_presence
8+
existing = Pathname.new(__FILE__)
9+
not_existing = Pathname.new("not existing")
10+
assert_equal existing, existing.existence
11+
assert_nil not_existing.existence
12+
end
13+
end

guides/source/active_support_core_extensions.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4055,3 +4055,18 @@ end
40554055
NOTE: Defined in `active_support/core_ext/load_error.rb`.
40564056

40574057
[LoadError#is_missing?]: https://api.rubyonrails.org/classes/LoadError.html#method-i-is_missing-3F
4058+
4059+
Extensions to Pathname
4060+
-------------------------
4061+
4062+
### `existence`
4063+
4064+
The [`existence`][Pathname#existence] method returns the receiver if the named file exists otherwise returns +nil+. It is useful for idioms like this:
4065+
4066+
```ruby
4067+
content = Pathname.new("file").existence&.read
4068+
```
4069+
4070+
NOTE: Defined in `active_support/core_ext/pathname/existence.rb`.
4071+
4072+
[Pathname#existence]: https://api.rubyonrails.org/classes/Pathname.html#method-i-existence

0 commit comments

Comments
 (0)