Skip to content

Instantly share code, notes, and snippets.

@baarde
Last active January 30, 2021 01:41
Show Gist options
  • Save baarde/f4368f6c8397c8d5c3d4f24345724996 to your computer and use it in GitHub Desktop.
Save baarde/f4368f6c8397c8d5c3d4f24345724996 to your computer and use it in GitHub Desktop.
Ruby Automatic Unegation
module AutomaticUnegation
def method_missing(name, *args, &block)
return super unless unegated = unegated_method_name(name)
!send(unegated, *args, &block)
end
def respond_to?(name, include_private = false)
super || unegated_method_name(name) != nil
end
private
def unegated_method_name(name)
name = name.to_s
return unless name.start_with?('not_') && name.end_with?('?')
unegated = name[4..-1].to_sym
return unegated if respond_to?(unegated)
end
end
class Object
include AutomaticUnegation
end
string = "Hello world"
messages = [
:not_nil?,
:not_empty?,
:not_ascii_only?,
[:not_include?, 'world'],
[:not_respond_to?, :not_nil?],
:not_not_unicode_normalized?,
]
for message in messages
puts "#{[*message]} → #{string.send(*message)}"
end
# [:not_nil?] → true
# [:not_empty?] → true
# [:not_ascii_only?] → false
# [:not_include?, "world"] → false
# [:not_respond_to?, :not_nil?] → false
# [:not_not_unicode_normalized?] → true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment