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.
Want to read me more?
-
Store UI State in localStorage with Stimulus
Easily store user preferences in the browser's localStorage using Stimulus. -
Custom Confirm Dialog For Turbo and Rails
With Turbo you can override the default confirm diaog (Do you really want to…) with a bit of JavaScript. Rails Designer comes with three custom themes. -
Smarter Use of Stimulus' Action Parameters
Explore a way to remove duplicate methods out of your Stimulus controller and add configuration logic into your HTML instead.
Over to you…
What did you like about this article? Learned something knew? Found something is missing or even broken? 🫣 Let me (and others) know!
Comments are powered by Chirp Form
{{comment}}