Created
July 23, 2022 09:00
-
-
Save elct9620/27820c282cf8d0eb158f352eab092e2f to your computer and use it in GitHub Desktop.
Ruby's IoC with dry-container and dry-auto_inject
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
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) |
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
require_relative './app/controllers/game_controller.rb' | |
app = lambda do |env| | |
# ... | |
controller = GameController.new(params: { id: '...' }) | |
ret = controller.start | |
# ... | |
end | |
run app |
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
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 |
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
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