Skip to content

Instantly share code, notes, and snippets.

@lwoodson
Created November 6, 2012 13:30
Show Gist options
  • Save lwoodson/4024744 to your computer and use it in GitHub Desktop.
Save lwoodson/4024744 to your computer and use it in GitHub Desktop.
Ruby service locator proposal. The irb.rb file defines 2 services (first and second) and leverages them in the Domain class.
require 'service_locator'
# Declare our services
Services.instance.config do
service :first, "this is"
service :second, " a test"
end
# See that ServiceDependent has convenience methods defined to access services.
puts ServiceDependent.instance_methods
# See that you can access services directly through the Services singleton.
Services.instance.service[:foo]
Services.instance.service[:bar]
# Define a domain class that is ServiceDependent and leverages the service
# accessor convenience methods to perform business ops.
class Domain
include ServiceDependent
def a_business_operation
first + second
end
end
# See that the business op succeeds.
domain = Domain.new
domain.a_business_operation
require 'singleton'
module ServiceDependent
end
class Services
include Singleton
attr_reader :services
def initialize
@services = {}
end
def service(key, svc=nil)
if svc.nil?
@services[key.to_sym]
else
@services[key.to_sym] = svc
end
end
def config(&block)
# Provides access to service method in configuration block.
self.instance_exec &block
# for each mapped service, define a convenience method in ServiceDependent to access it.
@services.each do |sym, svc|
ServiceDependent.send(:define_method, sym) { Services.instance.services[sym] }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment