In the overview section, we introduced the design for helpers. They are modules that enrich views’ behaviors. Because they are just Ruby modules, we can create our own helpers.

Example

Imagine we need (for some reason) a helper that shuffles the characters of a string and we want it to be available in our views.

First, let’s define a Web::Helpers::Shuffler module, and put it within a new helpers directory.

  1. # app/web/helpers/shuffler.rb
  2. module Web
  3. module Helpers
  4. module Shuffler
  5. private
  6. SEPARATOR = ''.freeze
  7. def shuffle(string)
  8. string
  9. .encode(Encoding::UTF_8, invalid: :replace)
  10. .split(SEPARATOR).shuffle.join
  11. end
  12. end
  13. end
  14. end

There is NO coupling between the file name and the name of the module. We can define this code where and how we want.

Now let’s make this helper available to use by editing our app’s application.rb. First, add that new helpers directory to the load paths of the application so it can be eagerly loaded. Second, include the Web::Helpers::Shuffler module in all the views. See the Views: Share Code section for low-level details.

  1. # apps/web/application.rb
  2. module Web
  3. class Application < Hanami::Application
  4. configure do
  5. # ...
  6. load_paths << [
  7. 'helpers',
  8. 'controllers',
  9. 'views'
  10. ]
  11. # ...
  12. view.prepare do
  13. include Hanami::Helpers
  14. include Web::Helpers::Shuffler
  15. end
  16. end
  17. end
  18. end

Please note that our custom helper will work even if we remove the include Hanami::Helpers line, because it’s just Ruby.