Skip to content

Instantly share code, notes, and snippets.

@vano468
Last active September 13, 2016 14:46
Show Gist options
  • Save vano468/1f6b8b45c88119f63c2b1fbcb1aa4d33 to your computer and use it in GitHub Desktop.
Save vano468/1f6b8b45c88119f63c2b1fbcb1aa4d33 to your computer and use it in GitHub Desktop.
class Container
module Dependent
def dependencies(*deps)
@dependencies ||= []
deps.each { |d| @dependencies << d }
@dependencies.uniq!
end
end
attr_reader :instances
def initialize
@instances = {}
end
def register(name, instance)
@instances[name] = instance
end
def get(name)
instances[name]
end
def inject(klass)
klass.instance_variable_get(:@dependencies).each do |d|
klass.instance_variable_set(:"@#{d}", get(d))
klass.send(:define_method, d) { self.class.instance_variable_get(:"@#{d}") }
end
end
end
class Worker
extend Container::Dependent
dependencies 'logger'
def perform
5.times { logger.info('Hello World!') }
end
end
class Logger
def info(str)
puts str
end
end
class SilentLogger
def info(str)
str
end
end
container = Container.new
container.register('logger', Logger.new)
container.inject(Worker)
Worker.new.perform
container.register('logger', SilentLogger.new)
container.inject(Worker)
Worker.new.perform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment