Last active
August 15, 2024 20:01
-
-
Save johncarney/217c802fe4432893ee07cc7e81d95bb2 to your computer and use it in GitHub Desktop.
Simple drop-in refinements module that replicates Rails's presence methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module PresenceRefinements | |
refine Object do | |
def blank? = (respond_to?(:empty?) ? !!empty? : !self) | |
def present? = !blank? | |
def presence = (self if present?) | |
end | |
# This bit is cribbed from https://github.com/rpanachi/core_ext | |
refine String do | |
BLANK_RE = /\A[[:space:]]*\z/ | |
ENCODED_BLANKS = Hash.new do |h, enc| | |
h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING) | |
end.freeze | |
def blank? | |
empty? || begin | |
BLANK_RE.match?(self) | |
rescue Encoding::CompatibilityError | |
ENCODED_BLANKS[self.encoding].match?(self) | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'presence_refinements' | |
using PresenceRefinements | |
["", " ", "\u00a0", "hi", nil, false, true, [], {}, %w[a b], { a: 1 }, 0, 1].each do |value| | |
puts "#{value.inspect}.blank? => #{value.blank?.inspect}, #{value.inspect}.presence => #{value.presence.inspect}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment