Codependent
Codependent is a simple, lightweight dependency injection library for Ruby.
Codependent by Example
Installation
gem install codependent
...or add Codependent to your Gemfile:
source 'https://rubygems.org'
gem 'codependent'
Basic Usage
Logger = Struct.new(:writer)
class UserRepository
def initialize(logger:)
@logger = logger
end
attr_reader :logger
end
class AccountRepository
attr_accessor :logger, :user_repository
end
container = Codependent::Container.new do
instance :logger do
from_value Logger.new
end
singleton :user_repository do
from_type UserRepository
depends_on :logger
end
singleton :account_repository do
from_type AccountRepository
inject_setters
depends_on :logger, :user_repository
end
instance :db_connection do
from_provider do |deps|
DB.open(deps[:connection_string])
end
end
instance :unchecked_dependency
from_type MetaprogammingIsCool
skip_checks
end
a_logger = container.resolve :logger
a_user_repo = container.resolve :user_repository
an_account_repo = container.resolve :account_repository
expect(an_account_repo.user_repository).to eq(a_user_repo)
expect(a_user_repo.logger).not_to eq(a_logger)
Advanced Usage
Managing Containers
Codependent::Manager.container :my_container do
instance :logger do
from_value Logger.new
end
end
a_logger = Codependent::Manager[:my_container].resolve(:logger)
Codependent::Manager.container?(:my_container)
Codependent::Manager.reset_container!(:my_container)
Codependent::Manager.reset!
Developing Codependent
Building from source
- Clone the repo.
- Install dependencies:
bundle install
- Run the tests:
bundle exec rake ci
- Build a local copy of the gem:
gem build codependent.gemspec
- Install the gem locally:
gem install ./codependent-0.2.gem
- Don't forget to version-bump the gemspec before publishing!