Prepare

In our settings (apps/web/application.rb), there is a code block that allows to share the code for all the views of our application. When a view includes the Web::View 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 have an application that only renders JSON. For each view we should specify the handled format. This can be tedious to do by hand, but we can easily DRY our code.

We craft a module in apps/web/views/accept_json.rb.

  1. # apps/web/views/accept_json.rb
  2. module Web
  3. module Views
  4. module AcceptJson
  5. def self.included(view)
  6. view.class_eval do
  7. format :json
  8. end
  9. end
  10. end
  11. end
  12. end

Then we can load the file and include the module in all the views of our application, using view.prepare.

  1. # apps/web/application.rb
  2. require_relative './views/accept_json'
  3. module Web
  4. class Application < Hanami::Application
  5. configure do
  6. # ...
  7. view.prepare do
  8. include Web::Views::AcceptJson
  9. end
  10. end
  11. end
  12. end

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