Skip to content

Instantly share code, notes, and snippets.

@elct9620
Created July 23, 2022 09:00
Show Gist options
  • Save elct9620/27820c282cf8d0eb158f352eab092e2f to your computer and use it in GitHub Desktop.
Save elct9620/27820c282cf8d0eb158f352eab092e2f to your computer and use it in GitHub Desktop.
Ruby's IoC with dry-container and dry-auto_inject
require 'dry-contaienr'
require 'dry-auto_inject'
# Singleton style container
class Container
extend Dry::Container::Mixin
namespace :repositories do
register(:games) { GameRepository.new }
register(:players) { PlayerRepository.new }
# ...
end
namespace :services do
register(:game) { GameService.new }
# ...
end
end
Injectable = Dry::AutoInject(Container)
require_relative './app/controllers/game_controller.rb'
app = lambda do |env|
# ...
controller = GameController.new(params: { id: '...' })
ret = controller.start
# ...
end
run app
require_relative '../../bootstrap.rb'
# Application Layer - Game-related actions
class GameController < BaseController
include Injectable[
'repositories.games',
game_service: 'services.game'
]
# ..
def start
@game = games.find(params[:id])
game_service.start(@game)
games.save(@game)
@game
rescue GameService::NotReadyError => e
# ...
end
end
require_relative '../../bootstrap.rb'
# Domain Layer - Game-related business logic
class GameService < BaseService
class NotReadyError < StandardError; end
include Injectable[
'repositories.players'
]
ALLOWED_PLAYERS = (3..5).freeze
def start(game)
in_game_players = players.in_game(id: game.id)
raise NotReadyError unless ALLOWED_PLAYERS.cover?(in_game_players.size)
game.start
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment