The nicest query methods

Sep 25, 2016

I often find myself creating methods checking equality against a string. Like so:

def domestic?
  type == domestic
end

def international?
  type == international
end

It provides a nice interface to query an object with and it can help isolate concrete knowledge within the class. Over time this can add bloat to your class definition, though. I recently discovered a trick to DRY up some of this logic with the ActiveSupport::StringInquirer class. As the documentation puts it:

Wrapping a string in this class gives you a prettier way to test for equality

How nice!

Now with any string, you can call inquiry (or ActiveSupport::StringInquirer.new(string)) and have a new, dynamically generated query method at your disposal. This is achieved with the use of method_missing. So make sure before you call inquiry that your string has been parameterized and snake cased.

shipping_type = 'domestic'.inquiry
=> "domestic"
shipping_type.domestic?
=> true