Tidy up your Rails code with `inquiry`

This short article is less product-engineering/UI focused, but does help you as a developer write tidier code. For Rails Designer v1 I refactored some code in the components. One the of the improvements I made was using inquiry more.

I mentioned this ActiveSupport extension in this this article about lesser known Rails helpers too, but I thought it worthy of its own article.

So previously a component looked like this:

class DropdownComponent
  def initialize(theme: "light")
    @theme = theme
  end

  erb_template <<~ERB
    <%= tag.div "content", class: class_names("block, {"bg-white": light_theme?, "bg-black": dark_theme?}) %>
  ERB

  private

   def light_theme? = @theme == "light"
   def dark_theme? = @theme == "dark"
end

I personally like a (internal) API like this; it helps with reading the code instead of doing mental gymnastics needed to parse the variable (@theme) and its value ("light" or "dark").

So I was pretty happy with this code, but an annoyance arose when more themes would be added. So instead of writing separate methods for each option, I reached for inquiry.

The above component was rewritten like this:

class DropdownComponent
  def initialize(theme: "light")
    @theme = theme.inquiry
  end

  erb_template <<~ERB
    <%= tag.div "content", class: class_names("block, {"bg-white": @theme.light?, "bg-black": @theme.dark?}) %>
  ERB
end

One could argue @theme.light? reads worse than light_theme?, but I feel like its an improvement overall:

  • less lines of code in the class;
  • using a first-party helper from Rails/ActiveSupport;
  • no mental overhead on what to name the extra method(s).

As I pointed out in the article above, inquiry can also be used on arrays: ["pending", "active"].inquiry.pending? # => true.

This is one of those helpers that once you know about it, you see use for it everywhere.

Get UI & Product Engineering Insights for Rails Apps (and product updates!)

Published at . Last updated at . Have suggestions or improvements on this content? Do reach out.

UI components for Ruby on Rails apps

$ 129 one-time
payment

Get Access
  • One-time Payment

  • Access to the Entire Library

  • Built using ViewComponent

  • Designed with Tailwind CSS

  • Enhanced with Hotwire