Skip to content

Commit

Permalink
Added String#presence (#8345)
Browse files Browse the repository at this point in the history
  • Loading branch information
igor-alexandrov authored and Brian J. Cardiff committed Oct 21, 2019
1 parent 8125cc9 commit 16abc5d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,12 @@ describe "String" do
it { "hello".blank?.should be_false }
end

describe "presence" do
it { " \t\n".presence.should be_nil }
it { "\u{1680}\u{2029}".presence.should be_nil }
it { "hello".presence.should eq("hello") }
end

describe "index" do
describe "by char" do
it { "foo".index('o').should eq(1) }
Expand Down
13 changes: 13 additions & 0 deletions src/nil.cr
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,19 @@ struct Nil
raise NilAssertionError.new
end

# Returns `self`.
# This method enables to call the `presence` method (see `String#presence`) on a union with `Nil`.
# The idea is to return `nil` when the value is `nil` or empty.
#
# ```
# config = {"empty" => ""}
# config["empty"]?.presence # => nil
# config["missing"]?.presence # => nil
# ```
def presence
self
end

def clone
self
end
Expand Down
19 changes: 19 additions & 0 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2402,6 +2402,25 @@ class String
true
end

# Returns `self` unless `#blank?` is `true` in which case it returns `nil`.
#
# ```
# "a".presence # => "a"
# "".presence # => nil
# " ".presence # => nil
# " a ".presence # => " a "
# nil.presence # => nil
#
# config = {"empty" => ""}
# config["empty"]?.presence || "default" # => "default"
# config["missing"]?.presence || "default" # => "default"
# ```
#
# See also: `Nil#presence`.
def presence : self?
self if !blank?
end

def ==(other : self)
return true if same?(other)
return false unless bytesize == other.bytesize
Expand Down

0 comments on commit 16abc5d

Please sign in to comment.