Created
May 7, 2021 06:51
-
-
Save jodosha/e468367848a1127343d91f2dc0adffd6 to your computer and use it in GitHub Desktop.
Code spike for hanami-api + dry-container + dry_auto-inject (see https://github.com/hanami/api/pull/26)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "bundler/setup" | |
require "hanami/api" | |
require "hanami/api/container" | |
class Routes | |
def url(name) | |
"/#{name}" | |
end | |
end | |
class MyApi < Hanami::API | |
extend Hanami::API::Container | |
register "routes" do | |
Routes.new | |
end | |
helpers do | |
@keys = [] | |
def self.import(*keys) | |
@keys << keys | |
@keys.flatten! | |
end | |
import("routes") | |
def self.included(base) | |
super | |
return if @keys.empty? | |
keys = @keys | |
base.class_eval do | |
include Import[*keys] | |
end | |
end | |
def foo | |
"Foo" | |
end | |
def url(name) | |
routes.url(name) | |
end | |
end | |
root do | |
"hello #{foo} #{url(:root)}" | |
end | |
end | |
run MyApi.new |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "dry-container" | |
require "dry-auto_inject" | |
module Hanami | |
class API | |
module Container | |
def self.extended(base) | |
super | |
container = Class.new do | |
extend Dry::Container::Mixin | |
end | |
base.const_set(:Container, container) | |
base.const_set(:Import, Dry::AutoInject(container)) | |
base.const_get(:BlockContext).extend(BlockContext) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def register(key, &blk) | |
self::Container.register(key, &blk) | |
end | |
end | |
module BlockContext | |
def self.extended(base) | |
super | |
base.class_eval do | |
@keys = [] | |
end | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def included(base) | |
super | |
return if @keys.empty? | |
keys = @keys | |
base.class_eval do | |
include Import[*keys] | |
end | |
end | |
def import(*keys) | |
@keys << keys | |
@keys.flatten! | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment