Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hanami::API::Container #27

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft

Hanami::API::Container #27

wants to merge 3 commits into from

Conversation

jodosha
Copy link
Member

@jodosha jodosha commented May 12, 2021

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 #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 #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

@jodosha jodosha added this to the v0.3.0 milestone May 12, 2021
@jodosha jodosha self-assigned this May 12, 2021
@jodosha jodosha changed the base branch from master to main June 15, 2021 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant