Skip to content

Instantly share code, notes, and snippets.

@esquinas
Created July 20, 2020 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esquinas/87423c16b1373bccdd497a8613d5960b to your computer and use it in GitHub Desktop.
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/
# 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