Prepare

In our settings (lib/bookshelf.rb), there is code block that allows to share the code for all the mailers of our application. When a mailer includes the Hanami::Mailer module, that block code is yielded within the context of that class. This is heavily inspired by Ruby Module and its included hook.

Imagine we want to set a default sender for all the mailers. Instead of specifying it for each mailer, we can use a DRY approach.

We create a module:

  1. # lib/mailers/default_sender.rb
  2. module Mailers
  3. module DefaultSender
  4. def self.included(mailer)
  5. mailer.class_eval do
  6. from 'sender@bookshelf.org'
  7. end
  8. end
  9. end
  10. end

Then we include in all the mailers of our application, via prepare.

  1. # lib/bookshelf.rb
  2. # ...
  3. Hanami.configure do
  4. # ...
  5. mailer do
  6. root 'lib/bookshelf/mailers'
  7. # See https://guides.hanamirb.org/mailers/delivery
  8. delivery :test
  9. prepare do
  10. include Mailers::DefaultSender
  11. end
  12. end
  13. end

Code included via prepare is available for ALL the mailers of an application.