Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active December 11, 2024 03:18
Show Gist options
  • Save bradgessler/9ff36ad2e3a1b2577e7037480bdfca58 to your computer and use it in GitHub Desktop.
Save bradgessler/9ff36ad2e3a1b2577e7037480bdfca58 to your computer and use it in GitHub Desktop.
Boolean Truther
# If you prefer TrueClass and FalseClass returns for predicate methods,
# you can `include Boolean::Truther` into your class to automatically generate
# ¿-prefixed methods that return true or false.
# Define a module to automatically generate the ¿-prefixed methods
module Boolean
module Truther
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def method_added(method_name)
return unless method_name.to_s.end_with?("?")
# Define a new method prefixed with ¿
define_method "¿#{method_name.to_s.chomp('?')}" do
!!send(method_name)
end
super
end
end
end
# Maybe you fancy yourself as a Boolean Falser.
Falser = Truther
end
# Define a class and include the BooleanTruther module
class Request
include Boolean::Truther
# Define a sample method in the class
def xhr?
nil
end
end
# Create an instance of the Truther class and call the generated method
request = Request.new
p request.¿xhr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment