Hello. I’m running into a situation where some of my application and provider configurations are getting cluttered with initialization code and am curious what the desired solution is for initializating dependencies in a Hanami application? Here’s how I’ve solved the problem for the moment:
Initializers
# demo/lib/demo/initializers/dry.rb
Dry::Schema.load_extensions :monads
Dry::Validation.load_extensions :monads
# demo/lib/demo/initializers/rack_attack.rb
require "rack/attack"
Rack::Attack.safelist("allow localhost") { |request| %w[127.0.0.1 ::1].include? request.ip }
Rack::Attack.throttle("requests by IP", limit: 100, period: 60, &:ip)
# demo/lib/demo/initializers/sequel.rb
require "sequel"
Sequel::Database.extension :constant_sql_override, :pg_enum
Sequel.database_timezone = :utc
Sequel.application_timezone = :local
Application
# demo/config/app.rb
require "hanami"
require "refinements/pathnames"
module Demo
class App < Hanami::App
using Refinements::Pathnames
# This line loads all initializers.
Pathname.require_tree root.join("lib/demo/initializers")
end
end
The Pathname firepower comes from the Refinements gem.
As you can see the above has some pros and cons:
-
Pros
- I’m using a dedicated
lib/demo/initializers
folder in order to add a separate file for any dependency that I need to initialize and configure. This definitely cleans up code that is awkward to put in the application configuration or provider files. - Each initializer is loaded alphabetically so order of initialization is always the same and guaranteed.
- I’m using a dedicated
-
Cons
- Use of
demo/lib/demo/initializers
doesn’t feel right. It works but seems likeconfig/initializers
orapp/initializers
would be a better location? - These initializers are loaded outside of Dry System’s prepare, start, and shutdown lifecycle. Maybe that’s OK but would it be better to eager or lazy load initializers in a similar manner as the providers?
- Use of
Anyway, some thoughts. Curious what others are doing to tackle this situation and if there are better ways to do this better?