DEV Community

Rails Designer
Rails Designer

Posted on • Originally published at railsdesigner.com

Tidy up your Rails code with `inquiry`

This article was originally published on Rails Designer—The first professionally-designed UI components library for Rails.


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 might 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
railsdesigner profile image
Rails Designer

Got other creative or nifty ideas to use inquiry? Share them!