Container for application
We can create the global container for all hanami application. It will be super useful for initializers, some service objects, etc. In my mind I’m thinking about something like this:
# config/initializers/redis.rb
AppName::Container.register :redis do
ConnectionPool.new(size: 10, timeout: 3) { Redis.new(host: 'localhost', port: 6379) }
end
# spec/spec_helper.rb
AppName::Container.register :redis do
ConnectionPool.new(size: 10, timeout: 3) { MockRedis.new }
end
# in action, view, repository, etc
module Web::Controllers::Contributors
class Show
include Web::Action
def call(params)
user = container[:redis].with { |c| c.get(:key) }
end
end
end
In this example container[:redis]
is not a part of hanami. Developer should define this container for his application by self.
Why containers will good for developers:
- you can set special container for each envs
- you will have general way for working with shared code
- hanami-gems developers will have the general way to share gem code in hanami app
Ideas where you can use it now
container['interactors.interactor_name']
- Any code in
/config/initialization/ folder (for example I have
Markdown` class for converting md to html) - some api clients without global configuration (
twitter = Twitter.new(config); twitter.tweet('text')
) - any services from
lib/
folder