Skip to content

Commit

Permalink
add Pathname#existence
Browse files Browse the repository at this point in the history
  • Loading branch information
timoschilling committed Nov 25, 2021
1 parent 00fb4e6 commit 1a14bcb
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
8 changes: 8 additions & 0 deletions activesupport/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
* Add `Pathname#existence`.

```ruby
Pathname.new("file").existence&.read
```

*Timo Schilling*

* Remove deprecate `ActiveSupport::Multibyte::Unicode.default_normalization_form`.

*Rafael Mendonça França*
Expand Down
3 changes: 3 additions & 0 deletions activesupport/lib/active_support/core_ext/pathname.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# frozen_string_literal: true

require "active_support/core_ext/pathname/existence"
21 changes: 21 additions & 0 deletions activesupport/lib/active_support/core_ext/pathname/existence.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# frozen_string_literal: true

class Pathname
# Returns the receiver if the named file exists otherwise returns +nil+.
# <tt>pathname.existence</tt> is equivalent to
#
# pathname.existence? ? object : nil
#
# For example, something like
#
# content = pathname.read if pathname.exist?
#
# becomes
#
# content = pathname.existence&.read
#
# @return [Pathname]
def existence
self if exist?
end
end
13 changes: 13 additions & 0 deletions activesupport/test/core_ext/pathname/existence_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# frozen_string_literal: true

require_relative "../../abstract_unit"
require "active_support/core_ext/pathname/existence"

class PathnameExistenceTest < ActiveSupport::TestCase
def test_presence
existing = Pathname.new(__FILE__)
not_existing = Pathname.new("not existing")
assert_equal existing, existing.existence
assert_nil not_existing.existence
end
end

0 comments on commit 1a14bcb

Please sign in to comment.