Hanami includes an inflector that supports the pluralization, singularization and humanization of English words, as well as other transformations. This inflector is a Dry::Inflector instance.

Hanami uses the inflector internally for a variety of purposes, but it’s also available to use in your own code via the "inflector" component.

Configuring the inflector

To customize how particular words are inflected, use config.inflections in your app class.

  1. # config/app.rb
  2. require "hanami"
  3. module Bookshelf
  4. class App < Hanami::App
  5. config.inflections do |inflections|
  6. inflections.acronym "DB", "XML", "NBA", "WNBA"
  7. inflections.uncountable("hanami")
  8. end
  9. end
  10. end

A common reason for customization is to configure inflections to support desired class names and other constants. For example, the WNBA acronym above supports constants like Games::WNBA instead of Games::Wnba. See the autoloading guide for more detail.

Using the inflector in a component

Like "settings" and "logger", the inflector is available in your app and slice containers as an "inflector" component.

Use it in your own classes via the Deps mixin through include Deps["inflector"].

  1. # app/my_component.rb
  2. module Bookshelf
  3. class MyComponent
  4. include Deps["inflector"]
  5. def call
  6. inflector.pluralize("book") # => "books"
  7. inflector.singularize("books") # => "book"
  8. inflector.camelize("dry/inflector") # => "Dry::Inflector"
  9. inflector.classify("books") # => "Book"
  10. inflector.tableize("Book") # => "books"
  11. inflector.dasherize("best_selling_books") # => "best-selling-books"
  12. inflector.underscore("best-selling-books") # => "best_selling_books"
  13. inflector.demodulize("Bookshelf::MyComponent") # => "MyComponent"
  14. inflector.humanize("hanami_inflector") # => "Hanami inflector"
  15. inflector.humanize("author_id") # => "Author"
  16. inflector.ordinalize(1) # => "1st"
  17. inflector.ordinalize(2) # => "2nd"
  18. end
  19. end
  20. end

Replacing the inflector

If needed, you can replace the inflector by providing your own. Your replacement inflector should be another Dry::Inflector instance or provide the same interface.

  1. # config/app.rb
  2. require "hanami"
  3. require "my_inflector"
  4. module Bookshelf
  5. class App < Hanami::App
  6. config.inflector = MyInflector.new
  7. end
  8. end