Skip to content

Instantly share code, notes, and snippets.

@cstorey
Last active December 11, 2015 09:49
Show Gist options
  • Save cstorey/4582571 to your computer and use it in GitHub Desktop.
Save cstorey/4582571 to your computer and use it in GitHub Desktop.
# 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