Created
July 20, 2020 12:23
-
-
Save esquinas/87423c16b1373bccdd497a8613d5960b to your computer and use it in GitHub Desktop.
Best-of-both-worlds example (DI + hard-coded constants) from this article: https://www.rubypigeon.com/posts/dependency_injection_containers_vs_hardcoded_constants/
This file contains hidden or 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
# Usage: | |
# - To load default dependencies: `register_user = RegisterUser.build` | |
# - To inject own dependencies (for testing or reuse): | |
# ```rb | |
# register_admin = RegisterUser.new(validator: AdminValidator.new, repo: AdminRepository.new) | |
# ``` | |
class RegisterUser | |
attr_reader :validator, :repo | |
def self.build | |
new( | |
validator: UserValidator.new, | |
repo: UserRepository.new, | |
) | |
end | |
def initialize(validator:, repo:) | |
@validator = validator | |
@repo = repo | |
end | |
def call(params) | |
if validator.validate(params) | |
repo.save(params) | |
else | |
nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment