Hanami has a convenient way to load commands from third party gems, so if you want to add a Hanami compatible gem, you only have to add it inside your project’s Gemfile in the :plugins group.

  1. # Gemfile
  2. group :plugins do
  3. gem "hanami-reloader"
  4. end

Add a command

Imagine you want to build a fictional gem called hanami-webpack with a CLI command: hanami webpack setup.

  1. # lib/hanami/webpack.rb
  2. module Hanami
  3. module Webpack
  4. module CLI
  5. class Setup < Hanami::CLI::Command
  6. def call(*)
  7. # setup code goes here...
  8. end
  9. end
  10. end
  11. end
  12. end
  13. Hanami::CLI.register "webpack setup", Hanami::Webpack::CLI::Setup

This code above will make the following command available:

  1. $ bundle exec hanami webpack setup

Hook into existing command

Third-party Hanami plugins can hook into existing commands, in order to enhance the default behavior. During the command execution lifecycle you can execute custom code before and/or after the command itself.

Let’s say we want to build a fictional gem hanami-database-analyzer, that prints database stats after db migrate is ran.

  1. # lib/hanami/database/analizer.rb
  2. module Hanami
  3. module Database
  4. module Analyzer
  5. class Stats
  6. def call(*)
  7. puts "The database has 23 tables"
  8. end
  9. end
  10. end
  11. end
  12. end
  13. Hanami::CLI::Commands.before("db migrate") { puts "I am about to migrate database.." }
  14. Hanami::CLI::Commands.after "db migrate", Hanami::Database::Analyzer::Stats.new

By running db migrate, the third-party code is executed:

  1. $ bundle exec hanami db migrate
  2. I am about to migrate database..
  3. # ...
  4. The database has 23 tables