api
api copied to clipboard
Hanami::API::Container
Feature
Allow to register deps to be used within the block context.
ℹ️ Convention: the name of the registration key is the same method that can be used in the block context. Example: register :redis will make the redis method available in block context.
💡 Good to know: registered deps can be used in helpers. See https://github.com/hanami/api/pull/26
Examples
⚠️ This feature requires to manually bundle dry-container and dry-auto_inject gems.
# Gemfile
gem "hanami-api"
# Manually add those gems to your Gemfile
gem "dry-container"
gem "dry-auto_inject"
Scenario 1: register and use a dependency directly in block endpoints.
# frozen_string_literal: true
require "hanami/api"
require "hanami/api/container"
require "logger"
class MyApp < Hanami::API
extend Hanami::API::Container+
register :logger do
Logger.new($stdout)
end
root do
logger.info("request GET /")
"hello"
end
end
Scenario 2: register a dependency and use it in helpers. See https://github.com/hanami/api/pull/26
# frozen_string_literal: true
require "hanami/api"
require "hanami/api/container"
require "logger"
class MyApp < Hanami::API
extend Hanami::API::Container
register :logger do
Logger.new($stdout)
end
helpers do
def redirect_to_root
logger.info("redirect to GET /")
redirect "/"
end
end
root do
logger.info("request GET /")
"hello"
end
get "/legacy" do
redirect_to_root
end
end