Providing custom inflections to dry-system

Over on Twitter, @dsisnero asked this:

how do you add an acronym in dry-system? i wan CLI instead of Cli in my codebase

I thought it would be best to answer here for longevity!

You can configure a Dry::System::Container with a custom inflector object. If you use a system like dry-inflector, you can register custom acronyms like so:

require "dry/inflector"

inflector = Dry::Inflector.new do |inflections|
  inflections.acronym "CLI", "HTTP", "XML" # ... etc.
end

Putting this together in a worked example, start with a system/inflector.rb:

require "dry/inflector"

module ExampleApp
  Inflector = Dry::Inflector.new do |inflections|
    inflections.acronym "CLI"
  end
end

Then a system/container.rb:

require "dry/system/container"
require "pathname"
require_relative "inflector"

module ExampleApp
  class Container < Dry::System::Container
    configure do |config|
      config.root = Pathname(__dir__).join("..").realpath
      config.inflector = Inflector
      config.component_dirs.add "lib"
    end
  end
end

Then add a lib/my_cli.rb:

class MyCLI
end

And then over in an IRB session or another Ruby script or similar, you can see this working:

require_relative "system/container"

container = ExampleApp::Container

container["my_cli"] # => #<MyCLI:0x00007f87ff8bb008>

Hope this helps!

4 Likes