lib/dry/rails/railtie.rb in dry-rails-0.3.0 vs lib/dry/rails/railtie.rb in dry-rails-0.4.0
- old
+ new
@@ -6,10 +6,12 @@
module Rails
# The railtie is responsible for setting up a container and handling reloading in dev mode
#
# @api public
class Railtie < ::Rails::Railtie
+ attr_reader :container_const_name
+
# This is needed because `finalize!` can reload code and this hook is called every-time
# in development env upon a request (in production it's called just once during booting)
config.to_prepare do
Railtie.finalize!
end
@@ -21,18 +23,18 @@
#
# @api public
#
# rubocop:disable Metrics/AbcSize
def finalize!
+ @container_const_name ||= Dry::Rails::Container.container_constant
+
stop_features if reloading?
root_path = ::Rails.root
container = Dry::Rails.create_container(
root: root_path,
- name: name,
- default_namespace: name.to_s,
inflector: default_inflector,
system_dir: root_path.join("config/system"),
bootable_dirs: [root_path.join("config/system/boot")]
)
@@ -40,14 +42,20 @@
container.use :env, inferrer: -> { ::Rails.env }
container.register(:railtie, self)
container.register(:inflector, default_inflector)
- set_or_reload(:Container, container)
+ # Remove previously defined constants, if any, so we don't end up with
+ # unsused constants in app's namespace when a name change happens.
+ remove_constant(container.auto_inject_constant)
+ remove_constant(container.container_constant)
Dry::Rails.evaluate_initializer(container)
+ @container_const_name = container.container_constant
+
+ set_or_reload(container.container_constant, container)
set_or_reload(container.auto_inject_constant, container.injector)
container.features.each do |feature|
container.boot(feature, from: :rails)
end
@@ -76,18 +84,18 @@
#
# @return [Dry::Rails::Container]
#
# @api public
def container
- app_namespace.const_get(:Container, false)
+ app_namespace.const_get(container_const_name, false)
end
# Return true if we're in code-reloading mode
#
# @api private
def reloading?
- app_namespace.const_defined?(:Container, false)
+ app_namespace.const_defined?(container_const_name, false)
end
# Return the default system name
#
# In the dry-system world containers are explicitly named using symbols, so that you can
@@ -124,19 +132,18 @@
ActiveSupport::Inflector
end
# @api private
def set_or_reload(const_name, const)
- if app_namespace.const_defined?(const_name, false)
- app_namespace.__send__(:remove_const, const_name)
- end
-
+ remove_constant(const_name)
app_namespace.const_set(const_name, const)
end
# @api private
def remove_constant(const_name)
- app_namespace.__send__(:remove_const, const_name)
+ if app_namespace.const_defined?(const_name, false)
+ app_namespace.__send__(:remove_const, const_name)
+ end
end
end
end
end