From Strings to Booleans: Meet ActiveSupport::StringInquirer in Ruby on Rails

ActiveSupport::StringInquirer is a cool class in Ruby on Rails that comes in handy to deal with strings as boolean-like objects. It’s great for making conditional logic simpler and improving our code readability.

When you wrap a string with this class, it gives you a snazzier way to check for equality. All you need to do is create a StringInquirer object, just like we’re showcasing below.

Create a StringInquirer object from a string

For instance, let’s say our user can choose between dark mode and light mode when using our app. We could instantiate a StringInquirer object like this:

theme = ActiveSupport::StringInquirer.new("dark_mode")

Working with booleans thanks to StringInquirer

Then we can simply use the boolean format to check if the string matches that value:

if theme.dark_mode?
puts "User prefers dark mode"
else
puts "User prefers light mode"
end

This is more readable than directly comparing strings and makes the code more expressive. Following with the example, assuming we had a class to manage user preferences, we could have something like this:

class UserPreferences
attr_accessor :theme

def initialize(theme)
@theme = ActiveSupport::StringInquirer.new(theme)
end

def light_mode?
@theme.light_mode?
end

def dark_mode?
@theme.dark_mode?
end
end

# Using the class
user_prefs = UserPreferences.new("dark_mode")

if user_prefs.light_mode?
puts "User prefers light mode"
else
puts "User prefers dark mode"
end

Rails environments with StringInquirer

One common use case of the StringInquirer class is when asking for Rails environments. The value returned by Rails.env is wrapped in a StringInquirer object, so instead of calling this:

Rails.env == 'production'

We call this:

Rails.env.production?

In summary, ActiveSupport::StringInquirer provides us with an object-oriented interface for working with strings, making our code more readable and expressive. You can check out the official documentation here if you want.