A quick experiment trying to replicate the cake pattern example from Jonas Bonér's post Real-World Scala: Dependency Injection (DI) in ruby.
-
-
Save cstorey/4582571 to your computer and use it in GitHub Desktop.
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
# From Jonas Bonér's post on The Cake Pattern | |
module UserRepositoryComponent | |
class UserRepository | |
def authenticate(user) | |
puts "Authenticating user: #{user}" | |
user | |
end | |
def create(user) | |
puts "Creating user: #{user}" | |
end | |
def delete(user) | |
puts "Deleting user: #{user}" | |
end | |
end | |
end | |
module UserServiceComponent # this: UserRepositoryComponent | |
def self.included (klass) | |
userServiceWithRepository = Class.new(UserServiceComponent::UserService) do | |
# using def here will cause us to lose a reference to the closed-over | |
# environment, and hence klass. | |
define_method :userRepository do | |
klass.userRepository | |
end | |
end | |
klass.const_set(:UserService, userServiceWithRepository) | |
end | |
class UserService | |
User = Struct.new(:username, :password) | |
def authenticate(username, password) | |
userRepository.authenticate(username, password) | |
end | |
def create(username, password) | |
userRepository.create(User.new(username, password)) | |
end | |
def delete(user) | |
userRepository.delete(user) | |
end | |
end | |
end | |
module ComponentRegistry | |
include UserServiceComponent | |
def self.userService | |
@userService ||= UserService.new | |
end | |
include UserRepositoryComponent | |
def self.userRepository | |
@userRepository ||= UserRepository.new | |
end | |
end | |
if $0 == __FILE__ | |
ComponentRegistry.userService.create('fred', 'moo') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment