Change inflections easily with the dry-inflector gem1 min read

Web developers commonly find themselves needing to change the inflection or formatting of certain words and phrases. For instance, moving between “ruby” and “rubies” or printing “3” as “3rd”.

Writing our own implementation of these is a little time-consuming. So, we’ll typically use a heavy framework like Rails’ built-in helper methods (e.g., titleize). These methods aren’t always what we need, and sometimes they’re overkill.

 

Enter the Dry-Inflector Gem

This library provides a super-simple, focused API to change plurality, casing, or even provide custom inflection rules.

Dry-inflector allows you to shift between class, module, method, or variable syntax commonly used in Ruby and other languages. As a result, it’s really helpful for metaprogramming.

It even has a handy API to convert numbers to ordinal format, which is a common frustration when trying to make some data more human readable.

Taken directly from their README:

inflector = Dry::Inflector.new

inflector.pluralize("book")    # => "books"
inflector.singularize("books") # => "book"

inflector.camelize("dry/inflector") # => "Dry::Inflector"
inflector.classify("books")         # => "Book"
inflector.tableize("Book")          # => "books"

inflector.dasherize("dry_inflector")  # => "dry-inflector"
inflector.underscore("dry-inflector") # => "dry_inflector"

inflector.demodulize("Dry::Inflector") # => "Inflector"

inflector.humanize("dry_inflector")    # => "Dry inflector"
inflector.humanize("author_id")        # => "Author"

inflector.ordinalize(1)  # => "1st"
inflector.ordinalize(2)  # => "2nd"
inflector.ordinalize(3)  # => "3rd"
inflector.ordinalize(10) # => "10th"
inflector.ordinalize(23) # => "23rd"

Go check them out here:

https://github.com/dry-rb/dry-inflector

Have you found any new or lesser-known gems that have proven useful to you? I’d love to hear about that in the comments below.

As always, thanks for reading.

I’m a full-stack web developer from Seattle. I love building software with an eye for quality and writing about the process.

Leave a Reply

Your email address will not be published. Required fields are marked *