Skip to content

Commit 1a14bcb

Browse files
add Pathname#existence
1 parent 00fb4e6 commit 1a14bcb

File tree

4 files changed

+45
-0
lines changed

4 files changed

+45
-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

0 commit comments

Comments
 (0)