Created
July 28, 2021 17:46
-
-
Save alessandro-fazzi/a2ddc9c504af10a99e7a2b3cee8bc951 to your computer and use it in GitHub Desktop.
LightService Organizer with dependency injection
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
# "Repository" class for all app dependencies | |
module App | |
class Dependencies | |
def self.deps | |
{ | |
'increment' => 1, | |
'test_increment' => 2 | |
} | |
end | |
def self.[](key) | |
deps[key] | |
end | |
end | |
Import = Dry::AutoInject(App::Dependencies) | |
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
source 'https://rubygems.org' | |
gem 'light-service' | |
gem 'dry-auto_inject' | |
gem 'pry-byebug' |
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 'light-service' | |
require 'dry-auto_inject' | |
require 'pry-byebug' | |
require './deps.rb' | |
class Organizer | |
extend LightService::Organizer | |
def self.call(counter:, injector: nil) | |
with(counter: counter, deps: injector&.new || Injector.new).reduce([One, Two]) | |
end | |
end | |
class One | |
extend LightService::Action | |
expects :counter, :deps | |
promises :result | |
executed do |context| | |
p "#{context.counter} + #{context.deps.increment}" | |
context.result = context.counter = context.counter + context.deps.increment | |
end | |
end | |
class Two | |
extend LightService::Action | |
expects :counter, :deps | |
promises :result | |
executed do |context| | |
p "#{context.counter} + #{context.deps.increment}" | |
context.result = context.counter = context.counter + context.deps.increment | |
end | |
end | |
class Injector | |
include App::Import['increment'] | |
end | |
class TestInjector | |
include App::Import['increment': 'test_increment'] | |
end | |
# binding.pry | |
puts 'Real dependecies' | |
outcome = Organizer.call(counter: 0) | |
puts outcome.result | |
puts "\n===============\n\n" | |
puts 'Test dependecies' | |
outcome = Organizer.call(counter: 0, injector: TestInjector) | |
puts outcome.result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment