Skip to content

Instantly share code, notes, and snippets.

@johncarney
Last active August 15, 2024 20:01
Show Gist options
  • Save johncarney/217c802fe4432893ee07cc7e81d95bb2 to your computer and use it in GitHub Desktop.
Save johncarney/217c802fe4432893ee07cc7e81d95bb2 to your computer and use it in GitHub Desktop.
Simple drop-in refinements module that replicates Rails's presence methods
# 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
# 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