• Dependencies specified with the Deps mixin
    • Config
    • Callbacks
    • Parameter validation schemas

    You can use action inheritance to ensure that broad collections of actions all have consistent key behaviors.

    For example, consider the following base action class.

    Any class that inherits from this will:

    • Have the object available to its instance methods
    • Expect JSON requests and return JSON respnses
    • Ensure that requests are authenticated based on the X-API-Token and return a 401 error if not
    1. # app/actions/books/index.rb
    2. module Bookshelf
    3. module Actions
    4. module Books
    5. end
    6. end
    7. end
    8. end

    When you create a new Hanami app, Hanami generates a standard base class for all your actions to inherit from.

    Hanami also generates a base action class for each slice.

    1. module Admin
    2. class Action < Hanami::Action
    3. end
    4. end

    These base classes can be a useful place to put any config or behavior that you want for every action in your app or slice.

    Leveraging action inheritance

    For example, you could make a new base class for a specific group of actions:

    Any classes within this namespace could inherit from Actions::UserProfile::Base and share common user authentication behaviour.

    Alternatively, for authentication behaviour that may need to be used across a range of disparate actions, you could also consider a module.

    1. # app/actions/authenticated_action.rb
    2. module Bookshelf
    3. module AuthenticatedAction
    4. action_class.before :authenticate_user!
    5. end
    6. private
    7. def authenticate_user!(request, response)
    8. # halt 401 unless ...
    9. end
    10. end
    11. end
    12. end