- 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
# app/actions/books/index.rb
module Bookshelf
module Actions
module Books
end
end
end
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.
module Admin
class Action < Hanami::Action
end
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.
# app/actions/authenticated_action.rb
module Bookshelf
module AuthenticatedAction
action_class.before :authenticate_user!
end
private
def authenticate_user!(request, response)
# halt 401 unless ...
end
end
end
end