Skip to content

Instantly share code, notes, and snippets.

@sheldonh
Last active August 29, 2015 14:16
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 sheldonh/9b51325d2402d2f863a4 to your computer and use it in GitHub Desktop.
Save sheldonh/9b51325d2402d2f863a4 to your computer and use it in GitHub Desktop.
Ruby dependency injection without Spring
---
beans:
invoice_service:
class: InvoiceService
method: constructor
arguments:
- bean:billing_provider
- bean:asset_provider
- dry_run: true
billing_provider:
class: FreshBooksBillingProvider
method: constructor
arguments:
- url: https://fb.localdomain/ep
license_key: 497bca6b-50192c4c-8384f347-4a3ea754-082a7d70-45e041e2-9cfe07a1-3544d7e5
asset_provider:
class: AssetPointAssetProvider
method: constructor
arguments:
host: 192.168.22.42
port: 443
username: user
password: secret
# Here is what you could do with autowiring:
Bundler.require(:default)
config = #...
autowiring = Fabrique::AutoWiring.new(YAML.load(config.get_string("application_context")))
api = autowiring.get_bean("invoice_service")
# Here is the crap you need to add to do it programmatically:
# API gem does this
InvoiceServiceApiFactory = Fabrique::FactoryAdaptor::Method.new(
template: InvoiceService,
method: :new,
arguments: Fabrique::ArgumentAdaptor::Positional.new(:billing_provider, :asset_provider, [:properties])
)
InvoiceServiceProviderFactoryRegistry = Fabrique::Registry.new(name: "Invoice service billing provider registry", index_components: 2)
# A billing provider gem does this
FreshBooksBillingProviderFactory = Fabrique::FactoryAdaptor::Method.new(
template: FreshBooksBillingProvider,
method: :new,
arguments: Fabrique::ArgumentAdaptor::Keyword.new
)
InvoiceServiceProviderFactoryRegistry.register("billing", "freshbooks", FreshBooksBillingProviderFactory)
# An asset provider gem does this
AssetPointAssetProviderFactory = Fabrique::FactoryAdaptor::Method.new(
template: AssetPointAssetProviderFactory,
method: :new,
arguments: Fabrique::ArgumentAdaptor::Keyword.new(:host, :port, :username, :password)
)
InvoiceServiceProviderFactoryRegistry.register("asset", "assetpoint", AssetPointAssetProviderFactory)
# API consumer does this
Bundler.require(:default)
config = # ...
api = InvoiceServiceApiFactory.create(
billing_provider: InvoiceServiceProviderFactoryRegistry.find("billing", config.get_string("billing_provider")).create(
config.get_properties("billing_provider_properties")
),
asset_provider: InvoiceServiceProviderFactoryRegistry.find("asset", config.get_string("asset_provider")).create(
config.get_properties("asset_provider_properties")
)
properties: {dry_run: true}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment