Class: Torikago::EngineContainer

Inherits:
Object
  • Object
show all
Defined in:
lib/torikago/engine_container.rb,
sig/torikago.rbs

Overview

Owns the runtime for one registered module. When Ruby::Box is available it loads the module into an isolated Box; otherwise it falls back to the host process for development and tests.

Constant Summary collapse

BUNDLER_SETUP_ENV_MUTEX =

Returns:

  • (Mutex)
Mutex.new
TORIKAGO_RUNTIME_CONSTANTS =

Returns:

  • (Array[Symbol])
%i[
  Error
  DependencyError
  BoxUnavailableError
  PublicApiError
  GemfileOverrideError
  Gateway
].freeze
FRAMEWORK_CONSTANTS =

Returns:

  • (Array[Symbol])
%i[
  Rails
  ActionController
  ActionDispatch
  ActionView
  ActiveModel
  ActiveRecord
  ActiveSupport
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, module_root:, entrypoint: nil, rails_engine: false, setup: nil, gemfile: nil, registered_roots: nil, box_factory: nil, gemfile_dependency_loader: nil, gem_activator: nil, root_constant_resolver: nil) ⇒ EngineContainer

Returns a new instance of EngineContainer.



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/torikago/engine_container.rb', line 28

def initialize(name:, module_root:, entrypoint: nil, rails_engine: false, setup: nil, gemfile: nil, registered_roots: nil, box_factory: nil, gemfile_dependency_loader: nil, gem_activator: nil, root_constant_resolver: nil)
  @name = name
  @module_root = Pathname(module_root)
  @entrypoint = entrypoint
  @rails_engine = rails_engine
  @setup = setup
  @gemfile = gemfile
  @registered_roots = registered_roots || [@module_root]
  @box_factory = box_factory
  @gemfile_dependency_loader = gemfile_dependency_loader || method(:load_gemfile_dependencies)
  @gem_activator = gem_activator || method(:activate_gem_dependency)
  @root_constant_resolver = root_constant_resolver
end

Instance Attribute Details

#box_factoryObject (readonly)

Returns the value of attribute box_factory.

Returns:

  • (Object)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def box_factory
  @box_factory
end

#entrypointString? (readonly)

Returns the value of attribute entrypoint.

Returns:

  • (String, nil)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def entrypoint
  @entrypoint
end

#gem_activatorObject (readonly)

Returns the value of attribute gem_activator.

Returns:

  • (Object)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def gem_activator
  @gem_activator
end

#gemfileString? (readonly)

Returns the value of attribute gemfile.

Returns:

  • (String, nil)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def gemfile
  @gemfile
end

#gemfile_dependency_loaderObject (readonly)

Returns the value of attribute gemfile_dependency_loader.

Returns:

  • (Object)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def gemfile_dependency_loader
  @gemfile_dependency_loader
end

#module_rootPathname (readonly)

Returns the value of attribute module_root.

Returns:

  • (Pathname)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def module_root
  @module_root
end

#nameSymbol, String (readonly)

Returns the value of attribute name.

Returns:

  • (Symbol, String)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def name
  @name
end

#registered_rootsArray[Pathname | String] (readonly)

Returns the value of attribute registered_roots.

Returns:

  • (Array[Pathname | String])


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def registered_roots
  @registered_roots
end

#root_constant_resolverRootConstantResolver? (readonly)

Returns the value of attribute root_constant_resolver.

Returns:



90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def root_constant_resolver
  @root_constant_resolver
end

#setupString? (readonly)

Returns the value of attribute setup.

Returns:

  • (String, nil)


90
91
92
# File 'lib/torikago/engine_container.rb', line 90

def setup
  @setup
end

Instance Method Details

#activate_gem_dependency(dependency) ⇒ Object

Parameters:

  • dependency (Hash[Symbol, untyped])

Returns:

  • (Object)


723
724
725
# File 'lib/torikago/engine_container.rb', line 723

def activate_gem_dependency(dependency)
  Kernel.send(:gem, dependency.fetch(:name), dependency.fetch(:requirement))
end

#apply_gemfile_overrides!Object

Returns:

  • (Object)


333
334
335
336
337
338
339
340
341
342
343
# File 'lib/torikago/engine_container.rb', line 333

def apply_gemfile_overrides!
  path = gemfile_path
  return unless path

  gemfile_dependencies.each do |dependency|
    gem_activator.call(dependency)
  rescue Gem::LoadError => e
    raise GemfileOverrideError,
          "failed to activate #{dependency.fetch(:name)} (#{dependency.fetch(:requirement)}) for #{name}: #{e.message}"
  end
end

#attach_rails_helpers!Object

Returns:

  • (Object)


179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/torikago/engine_container.rb', line 179

def attach_rails_helpers!
  helper_modules = Dir[module_root.join("app/helpers/**/*_helper.rb").to_s].sort.filter_map do |path|
    constant_name = rails_constant_name_for(path)
    resolve_runtime_class(constant_name) if constant_name
  rescue NameError
    nil
  end
  return if helper_modules.empty?

  rails_controller_files.each do |path|
    constant_name = rails_constant_name_for(path)
    next unless constant_name

    controller = resolve_runtime_class(constant_name)
    next unless controller.respond_to?(:helper)

    helper_modules.each { |helper_module| controller.helper(helper_module) }
  rescue NameError
    next
  end
end

#boot_controller_runtime!Object

Returns:

  • (Object)


133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/torikago/engine_container.rb', line 133

def boot_controller_runtime!
  boot_runtime!
  return if rails_engine?
  return if @controller_runtime_booted

  files = controller_runtime_files - runtime_files
  if isolated_box_enabled?
    without_bundler_setup_env do
      with_box_runtime_errors do
        install_rails_runtime_support!
        prepare_rails_application_controller_in_box!
        load_runtime_files_into_box!(files)
        attach_rails_helpers!
      end
    end
  else
    files.each do |path|
      load path
      normalize_rails_constant_name!(path)
    end
    attach_rails_helpers!
  end

  @controller_runtime_booted = true
end

#boot_runtime!Object

Returns:

  • (Object)


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/torikago/engine_container.rb', line 92

def boot_runtime!
  return if @booted

  files = runtime_files
  gemfile_dependencies
  if isolated_box_enabled?
    without_bundler_setup_env do
      # The Box starts with an independent load path and constant table, so
      # boot has to copy enough host context before loading module code.
      with_box_runtime_errors do
        prepare_box!
        prepend_gemfile_require_paths_to_box!
        install_host_runtime_bridges!
        load_setup_hook_into_box!
        ensure_root_namespace_in_box!
        prepare_rails_application_controller_in_box!

        files.each do |path|
          box.load(path)
          normalize_rails_constant_name!(path)
        end
        attach_rails_helpers!
      end
    end
  else
    # Non-Box mode preserves the same public behavior while giving up
    # runtime isolation. This keeps local development usable on normal Ruby.
    apply_gemfile_overrides!
    load_setup_hook!
    ensure_root_namespace!

    files.each do |path|
      load path
      normalize_rails_constant_name!(path)
    end
    attach_rails_helpers!
  end

  @booted = true
end

#boxObject

Returns:

  • (Object)


460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/torikago/engine_container.rb', line 460

def box
  @box ||= if box_factory
             box_factory.call
           else
             without_bundler_setup_env { Ruby::Box.new }
           end
rescue BoxUnavailableError
  raise
rescue StandardError => e
  raise unless ENV["RUBY_BOX"] == "1"

  raise BoxUnavailableError, "Ruby::Box is unavailable for module #{name}: #{e.message}"
end

#call(env) ⇒ Object

Dispatches a Rack request to a Rails::Engine owned by this module. Route recognition happens against the Box-local engine, then the Box-local controller class is invoked directly so Rails never constantizes the controller in the host application's Object namespace.

Parameters:

  • env (Hash[String, untyped])

Returns:

  • (Object)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/torikago/engine_container.rb', line 54

def call(env)
  unless rails_engine?
    raise ArgumentError, "module #{name} is not registered with rails_engine: true"
  end

  CurrentExecution.with_box(name) do
    boot_runtime!
    route, rack_response = recognize_route(env)
    return rack_response if rack_response

    controller = resolve_runtime_class("#{camelize_controller(route.fetch(:controller))}Controller")

    dispatch_controller_action(env, controller, route.fetch(:action), route)
  end
end

#camelize(segment) ⇒ String

Parameters:

  • segment (String)

Returns:

  • (String)


598
599
600
# File 'lib/torikago/engine_container.rb', line 598

def camelize(segment)
  segment.split("_").map(&:capitalize).join
end

#camelize_controller(controller_path) ⇒ String

Parameters:

  • controller_path (String)

Returns:

  • (String)


318
319
320
# File 'lib/torikago/engine_container.rb', line 318

def camelize_controller(controller_path)
  controller_path.to_s.split("/").map { |segment| camelize(segment) }.join("::")
end

#controller_runtime_filesArray[String]

Returns:

  • (Array[String])


398
399
400
401
402
403
404
405
406
# File 'lib/torikago/engine_container.rb', line 398

def controller_runtime_files
  [
    *library_files,
    *Dir[module_root.join("app/models/**/*.rb").to_s].sort,
    *Dir[module_root.join("app/helpers/**/*.rb").to_s].sort,
    *rails_controller_files,
    *Dir[public_api_root.join("**/*.rb").to_s].sort
  ].uniq
end

#dispatch_controller(env, controller_name:, action_name:) ⇒ Object

Dispatches a host-owned route to a controller that belongs to this module. Unlike #call, route recognition has already happened in the host router, so this path does not require a Rails::Engine inside the module.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/torikago/engine_container.rb', line 73

def dispatch_controller(env, controller_name:, action_name:)
  CurrentExecution.with_box(name) do
    boot_controller_runtime!
    controller = resolve_runtime_class(controller_name)

    dispatch_controller_action(
      env,
      controller,
      action_name,
      controller: controller_name,
      action: action_name.to_s
    )
  end
end

#dispatch_controller_action(env, controller, action_name, path_parameters) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/torikago/engine_container.rb', line 166

def dispatch_controller_action(env, controller, action_name, path_parameters)
  current_parameters = env.fetch(
    "action_dispatch.request.path_parameters",
    Hash.new
  )
  request_env = env.merge(
    "action_dispatch.request.path_parameters" =>
      current_parameters.merge(path_parameters.transform_keys(&:to_sym))
  )

  controller.action(action_name).call(request_env)
end

#ensure_root_namespace!Object

Returns:

  • (Object)


440
441
442
443
444
445
# File 'lib/torikago/engine_container.rb', line 440

def ensure_root_namespace!
  namespace = camelize(name.to_s)
  return if Object.const_defined?(namespace, false)

  Object.const_set(namespace, Module.new)
end

#ensure_root_namespace_in_box!Object

Returns:

  • (Object)


447
448
449
450
451
452
# File 'lib/torikago/engine_container.rb', line 447

def ensure_root_namespace_in_box!
  namespace = camelize(name.to_s)
  return if box.const_defined?(namespace, false)

  box.const_set(namespace, Module.new)
end

#exact_version_gemfile_dependencies(path) ⇒ Array[Hash[Symbol, String]]

Parameters:

  • path (Pathname)

Returns:

  • (Array[Hash[Symbol, String]])


707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/torikago/engine_container.rb', line 707

def exact_version_gemfile_dependencies(path)
  path.read.each_line.filter_map do |line|
    match = line.match(/^\s*gem\s+["']([^"']+)["']\s*,\s*["']=\s*([^"']+)["']/)
    next unless match

    gem_name = match[1]
    version = match[2]
    next unless gem_name && version

    {
      name: gem_name,
      requirement: "= #{version}"
    }
  end
end

#gateway_model_filesArray[String]

Returns:

  • (Array[String])


550
551
552
553
554
555
556
# File 'lib/torikago/engine_container.rb', line 550

def gateway_model_files
  # Package APIs may depend on small PORO-style models. Active Record models
  # are skipped because Rails owns their loading and database connection.
  Dir[module_root.join("app/models/**/*.rb").to_s].sort.reject do |path|
    rails_model_file?(path)
  end
end

#gemfile_dependenciesArray[Hash[Symbol | String, untyped]]

Returns:

  • (Array[Hash[Symbol | String, untyped]])


355
356
357
358
359
360
# File 'lib/torikago/engine_container.rb', line 355

def gemfile_dependencies
  path = gemfile_path
  return Array.new unless path

  @gemfile_dependencies ||= gemfile_dependency_loader.call(path)
end

#gemfile_pathPathname?

Returns:

  • (Pathname, nil)


428
429
430
431
432
# File 'lib/torikago/engine_container.rb', line 428

def gemfile_path
  return unless gemfile

  module_root.join(gemfile)
end

#install_host_constant_bridge!(constant_name) ⇒ Object

Parameters:

  • constant_name (Symbol)

Returns:

  • (Object)


543
544
545
546
547
548
# File 'lib/torikago/engine_container.rb', line 543

def install_host_constant_bridge!(constant_name)
  return unless Object.const_defined?(constant_name, false)
  return if box.const_defined?(constant_name, false)

  box.const_set(constant_name, Object.const_get(constant_name, false))
end

#install_host_runtime_bridges!Object

Returns:

  • (Object)


529
530
531
532
# File 'lib/torikago/engine_container.rb', line 529

def install_host_runtime_bridges!
  FRAMEWORK_CONSTANTS.each { |constant_name| install_host_constant_bridge!(constant_name) }
  install_rails_runtime_support! if rails_engine?
end

#install_rails_runtime_support!Object

Returns:

  • (Object)


534
535
536
537
538
539
540
541
# File 'lib/torikago/engine_container.rb', line 534

def install_rails_runtime_support!
  install_host_constant_bridge!(:ApplicationController)
  install_host_constant_bridge!(:ApplicationRecord)
  return unless Object.const_defined?(:ActiveSupport, false)
  return unless box.respond_to?(:require)

  box.require("active_support/core_ext/object/blank")
end

#install_root_constant_fallback!Object

Returns:

  • (Object)


506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/torikago/engine_container.rb', line 506

def install_root_constant_fallback!
  return unless box.respond_to?(:eval)

  resolver = root_constant_resolver || RootConstantResolver.new(registered_roots: registered_roots)
  box_torikago = box.const_get(:Torikago)
  box_torikago.const_set(:ROOT_CONSTANT_RESOLVER, resolver)
  box_torikago.const_set(:ROOT_CONSTANT_UNRESOLVED, resolver.unresolved)
  box.eval(<<~RUBY)
    module Torikago
      module RootConstantFallback
        def const_missing(name)
          resolved = ROOT_CONSTANT_RESOLVER.resolve(name)
          return resolved unless resolved.equal?(ROOT_CONSTANT_UNRESOLVED)

          super
        end
      end
    end

    Object.singleton_class.prepend(Torikago::RootConstantFallback)
  RUBY
end

#install_torikago_runtime_bridges!Object

Returns:

  • (Object)


496
497
498
499
500
501
502
503
504
# File 'lib/torikago/engine_container.rb', line 496

def install_torikago_runtime_bridges!
  box_torikago = box.const_get(:Torikago)

  TORIKAGO_RUNTIME_CONSTANTS.each do |constant_name|
    next if box_torikago.const_defined?(constant_name, false)

    box_torikago.const_set(constant_name, Torikago.const_get(constant_name, false))
  end
end

#installed_specs_for(gem_name, requirement) ⇒ Array[Gem::Specification]

Parameters:

  • gem_name (String)
  • requirement (String)

Returns:



690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/torikago/engine_container.rb', line 690

def installed_specs_for(gem_name, requirement)
  specs = Gem::Specification.find_all_by_name(gem_name, requirement)
  return specs unless specs.empty?

  gem_requirement = Gem::Requirement.new(requirement)
  Gem::Specification.dirs.flat_map do |specification_dir|
    Dir[File.join(specification_dir, "#{gem_name}-*.gemspec")].filter_map do |gemspec_path|
      spec = Gem::Specification.load(gemspec_path)
      next unless spec
      next unless spec.name == gem_name
      next unless gem_requirement.satisfied_by?(spec.version)

      spec
    end
  end
end

#invoke(public_api_class_name, method_name, constructor_args:, constructor_kwargs:, method_args:, method_kwargs:) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/torikago/engine_container.rb', line 42

def invoke(public_api_class_name, method_name, constructor_args:, constructor_kwargs:, method_args:, method_kwargs:)
  CurrentExecution.with_box(name) do
    public_api_class = resolve_public_api_class(public_api_class_name)
    instance = public_api_class.new(*constructor_args, **constructor_kwargs)
    instance.public_send(method_name, *method_args, **method_kwargs)
  end
end

#isolated_box_enabled?Boolean

Returns:

  • (Boolean)


454
455
456
457
458
# File 'lib/torikago/engine_container.rb', line 454

def isolated_box_enabled?
  return true if box_factory

  ruby_box_runtime_available?
end

#library_filesArray[String]

Returns:

  • (Array[String])


574
575
576
577
578
579
580
581
# File 'lib/torikago/engine_container.rb', line 574

def library_files
  all_files = Dir[module_root.join("lib/**/*.rb").to_s].sort
  monkey_patch_files = Dir[module_root.join("lib/monkey_patches/**/*.rb").to_s]

  # Monkey patches are only loaded through the explicit setup hook so a
  # module has to opt in to global-ish runtime changes.
  all_files - monkey_patch_files - rails_engine_entrypoint_files
end

#load_bundler_gem_dependencies(path) ⇒ Array[Hash[Symbol, untyped]]

Parameters:

  • path (Pathname)

Returns:

  • (Array[Hash[Symbol, untyped]])


641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# File 'lib/torikago/engine_container.rb', line 641

def load_bundler_gem_dependencies(path)
  require "bundler"

  lockfile = Pathname("#{path}.lock")
  definition = Bundler::Definition.build(path.to_s, lockfile.exist? ? lockfile.to_s : nil, nil)

  specs_by_name = definition.specs.each_with_object(Hash.new) do |spec, specs|
    specs[spec.name] ||= spec
  end

  definition.dependencies.filter_map do |dependency|
    spec = specs_by_name.fetch(dependency.name, nil)
    next unless spec

    requirement = dependency.requirement.to_s
    {
      name: dependency.name,
      requirement: requirement,
      require_paths: spec.full_require_paths
    }
  end
rescue LoadError => e
  raise GemfileOverrideError, "failed to load bundler for #{name}: #{e.message}"
rescue StandardError => e
  raise unless defined?(Bundler::BundlerError) && e.is_a?(Bundler::BundlerError)

  raise GemfileOverrideError, "failed to load gemfile for #{name}: #{e.message}"
end

#load_gemfile_dependencies(path) ⇒ Array[Hash[Symbol, untyped]]

Parameters:

  • path (Pathname)

Returns:

  • (Array[Hash[Symbol, untyped]])


602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/torikago/engine_container.rb', line 602

def load_gemfile_dependencies(path)
  unless path.exist?
    raise GemfileOverrideError, "gemfile not found for #{name}: #{path}"
  end

  # Prefer cheap local parsing for path and exact-version dependencies, then
  # fall back to Bundler for more complex Gemfiles.
  path_gem_dependencies = load_path_gem_dependencies(path)
  return path_gem_dependencies unless path_gem_dependencies.empty?

  installed_gem_dependencies = load_installed_gem_dependencies(path)
  return installed_gem_dependencies unless installed_gem_dependencies.empty?

  load_bundler_gem_dependencies(path)
end

#load_installed_gem_dependencies(path) ⇒ Array[Hash[Symbol, untyped]]

Parameters:

  • path (Pathname)

Returns:

  • (Array[Hash[Symbol, untyped]])


670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/torikago/engine_container.rb', line 670

def load_installed_gem_dependencies(path)
  dependencies = exact_version_gemfile_dependencies(path)
  return Array.new if dependencies.empty?

  dependencies.filter_map do |dependency|
    specs = installed_specs_for(dependency.fetch(:name), dependency.fetch(:requirement))
    spec = specs.max_by(&:version)
    unless spec
      raise GemfileOverrideError,
            "failed to load gemfile for #{name}: Could not find gem '#{dependency.fetch(:name)} (#{dependency.fetch(:requirement)})' in locally installed gems."
    end

    {
      name: spec.name,
      requirement: dependency.fetch(:requirement),
      require_paths: spec.full_require_paths
    }
  end
end

#load_path_gem_dependencies(path) ⇒ Array[Hash[Symbol, untyped]]

Parameters:

  • path (Pathname)

Returns:

  • (Array[Hash[Symbol, untyped]])


618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/torikago/engine_container.rb', line 618

def load_path_gem_dependencies(path)
  path.dirname.then do |gemfile_root|
    path.read.scan(/^\s*gem\s+["']([^"']+)["']\s*,\s*path:\s*["']([^"']+)["']/).filter_map do |gem_name, relative_path|
      next unless relative_path

      relative_path = relative_path.to_s
      gem_root = gemfile_root.join(relative_path)
      gemspec_path = gem_root.join("#{gem_name}.gemspec")
      gemspec_path = Dir[gem_root.join("*.gemspec").to_s].sort.first unless gemspec_path.exist?
      next unless gemspec_path

      spec = Gem::Specification.load(gemspec_path.to_s)
      next unless spec

      {
        name: spec.name,
        requirement: "= #{spec.version}",
        require_paths: spec.require_paths.map { |require_path| gem_root.join(require_path).to_s }
      }
    end
  end
end

#load_runtime_files_into_box!(files) ⇒ Object

Parameters:

  • files (Array[String])

Returns:

  • (Object)


159
160
161
162
163
164
# File 'lib/torikago/engine_container.rb', line 159

def load_runtime_files_into_box!(files)
  files.each do |path|
    box.load(path)
    normalize_rails_constant_name!(path)
  end
end

#load_setup_hook!Object

Returns:

  • (Object)


322
323
324
325
326
327
328
329
330
331
# File 'lib/torikago/engine_container.rb', line 322

def load_setup_hook!
  path = setup_path
  return unless path

  unless path.exist?
    raise LoadError, "setup not found for #{name}: #{path}"
  end

  load path.to_s
end

#load_setup_hook_into_box!Object

Returns:

  • (Object)


563
564
565
566
567
568
569
570
571
572
# File 'lib/torikago/engine_container.rb', line 563

def load_setup_hook_into_box!
  path = setup_path
  return unless path

  unless path.exist?
    raise LoadError, "setup not found for #{name}: #{path}"
  end

  box.load(path.to_s)
end

#normalize_rails_constant_name!(path) ⇒ Object

Parameters:

  • path (String)

Returns:

  • (Object)


243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/torikago/engine_container.rb', line 243

def normalize_rails_constant_name!(path)
  constant_name = rails_constant_name_for(path)
  return unless constant_name

  constant = resolve_runtime_class(constant_name)
  return unless constant.respond_to?(:define_singleton_method)

  # Ruby::Box includes an internal Box prefix in Module#name. Rails derives
  # helper and model constants from that value, so expose the conventional
  # application constant name to Rails while keeping the constant itself in
  # the Box.
  constant.define_singleton_method(:name) { constant_name }
  constant.remove_instance_variable(:@controller_path) if constant.instance_variable_defined?(:@controller_path)
  constant.remove_instance_variable(:@controller_name) if constant.instance_variable_defined?(:@controller_name)
  if path.include?("/app/controllers/") && constant.respond_to?(:prepend_view_path)
    constant.prepend_view_path(module_root.join("app/views").to_s)
  end
rescue NameError
  # Namespace-only files and files that define a differently named helper
  # do not need normalization.
  nil
end

#prepare_box!Object

Returns:

  • (Object)


484
485
486
487
488
489
490
491
492
493
494
# File 'lib/torikago/engine_container.rb', line 484

def prepare_box!
  return if @box_prepared

  box.load_path.replace($LOAD_PATH.dup) if box.respond_to?(:load_path)
  if box.respond_to?(:require)
    box.require("torikago/current_execution")
  end
  install_torikago_runtime_bridges!
  install_root_constant_fallback!
  @box_prepared = true
end

#prepare_rails_application_controller_in_box!Object

Returns:

  • (Object)


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/torikago/engine_container.rb', line 201

def prepare_rails_application_controller_in_box!
  return unless Object.const_defined?(:ActionController, false)
  return unless module_root.join("app/controllers/#{name}/application_controller.rb").exist?

  # FIXME: This workaround only supports controllers under the namespace
  # derived from the registered module name. Real top-level ActionController
  # subclasses still expose Ruby::Box's internal prefix to Rails inherited
  # hooks and helper lookup. Track support for non-namespaced controllers in:
  # https://github.com/se4weed/torikago/issues/15
  namespace_name = camelize(name.to_s)
  namespace = box.const_get(namespace_name)
  application_controller = if namespace.const_defined?(:ApplicationController, false)
                             namespace.const_get(:ApplicationController, false)
                           else
                             action_controller_base = Object.const_get(:ActionController).const_get(:Base)
                             namespace.const_set(:ApplicationController, Class.new(action_controller_base))
                           end

  application_controller.define_singleton_method(:name) { "#{namespace_name}::ApplicationController" }
  application_controller.define_singleton_method(:inherited) do |subclass|
    native_name = Module.instance_method(:name).bind_call(subclass)
    marker = "::#{namespace_name}::"
    conventional_name = if native_name&.include?(marker)
                          "#{namespace_name}::#{native_name.split(marker, 2).last}"
                        else
                          native_name
                        end
    # A class is still anonymous while inherited() runs. Do not let it
    # inherit ApplicationController's singleton name implementation.
    subclass.define_singleton_method(:name) { conventional_name }
    # ActiveSupport's default module_parents implementation constantizes
    # through the host Object. Return the already-resolved Box namespace.
    subclass.define_singleton_method(:module_parents) { [namespace] }
    # AbstractController tries to constantize "<Controller>Helper" in the
    # host Object namespace during inherited(). Module helpers live in this
    # Box, so they are attached explicitly after runtime files are loaded.
    subclass.define_singleton_method(:default_helper_module!) {}
    subclass.singleton_class.send(:private, :default_helper_module!)
    super(subclass)
  end
end

#prepend_gemfile_require_paths_to_box!Object

Returns:

  • (Object)


345
346
347
348
349
350
351
352
353
# File 'lib/torikago/engine_container.rb', line 345

def prepend_gemfile_require_paths_to_box!
  paths = gemfile_dependencies.flat_map { |dependency| Array(dependency[:require_paths] || dependency["require_paths"]) }
  return if paths.empty?
  return unless box.respond_to?(:load_path)

  # Put module-specific gems ahead of the host load path so the Box resolves
  # dependency versions from the module Gemfile first.
  box.load_path.replace(paths.map { |path| path.to_s } + box.load_path)
end

#public_api_rootPathname

Returns:

  • (Pathname)


417
418
419
420
421
422
423
424
425
426
# File 'lib/torikago/engine_container.rb', line 417

def public_api_root
  configured_entrypoint = entrypoint
  return module_root.join("app/package_api") if configured_entrypoint.nil?

  candidate = module_root.join(configured_entrypoint)
  return candidate if candidate.directory?
  return candidate unless candidate.extname == ".rb"

  candidate.dirname
end

#rails_constant_name_for(path) ⇒ String?

Parameters:

  • path (String)

Returns:

  • (String, nil)


266
267
268
269
270
271
272
273
274
275
276
# File 'lib/torikago/engine_container.rb', line 266

def rails_constant_name_for(path)
  app_root = module_root.join("app").to_s
  return unless path.start_with?("#{app_root}/")

  relative_path = path.delete_prefix("#{app_root}/")
  category, constant_path = relative_path.split("/", 2)
  return unless %w[controllers models helpers].include?(category)
  return unless constant_path&.end_with?(".rb")

  constant_path.delete_suffix(".rb").split("/").map { |segment| camelize(segment) }.join("::")
end

#rails_controller_filesArray[String]

Returns:

  • (Array[String])


408
409
410
411
412
413
414
415
# File 'lib/torikago/engine_container.rb', line 408

def rails_controller_files
  files = Dir[module_root.join("app/controllers/**/*.rb").to_s].sort
  application_controllers, other_controllers = files.partition do |path|
    File.basename(path) == "application_controller.rb"
  end

  application_controllers + other_controllers
end

#rails_engine?Boolean

Returns:

  • (Boolean)


590
591
592
# File 'lib/torikago/engine_container.rb', line 590

def rails_engine?
  @rails_engine
end

#rails_engine_entrypoint_filesArray[String]

Returns:

  • (Array[String])


583
584
585
586
587
588
# File 'lib/torikago/engine_container.rb', line 583

def rails_engine_entrypoint_files
  return Array.new unless rails_engine?

  path = module_root.join("lib/#{name}.rb")
  path.exist? ? [path.to_s] : Array.new
end

#rails_model_file?(path) ⇒ Boolean

Parameters:

  • path (String)

Returns:

  • (Boolean)


558
559
560
561
# File 'lib/torikago/engine_container.rb', line 558

def rails_model_file?(path)
  source = File.read(path)
  source.match?(/ActiveRecord::Base|<\s+\w+Record\b|^\s*validates\s/m)
end

#rails_runtime_filesArray[String]

Returns:

  • (Array[String])


386
387
388
389
390
391
392
393
394
395
396
# File 'lib/torikago/engine_container.rb', line 386

def rails_runtime_files
  [
    *rails_engine_entrypoint_files,
    *library_files,
    *Dir[module_root.join("app/models/**/*.rb").to_s].sort,
    *Dir[module_root.join("app/helpers/**/*.rb").to_s].sort,
    *rails_controller_files,
    *Dir[public_api_root.join("**/*.rb").to_s].sort,
    *Dir[module_root.join("config/routes.rb").to_s].sort
  ].uniq
end

#recognize_rails_route(routes, env) ⇒ Object

Parameters:

  • routes (Object)
  • env (Hash[String, untyped])

Returns:

  • (Object)

Raises:

  • (routing_error)


290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/torikago/engine_container.rb', line 290

def recognize_rails_route(routes, env)
  action_dispatch = Object.const_get(:ActionDispatch)
  request_class = action_dispatch.const_get(:Request)
  cascade_header = action_dispatch.const_get(:Constants).const_get(:X_CASCADE)
  request = request_class.new(env)
  recognized = nil

  routes.router.recognize(request) do |route, parameters|
    next unless route.app.matches?(request)

    request.path_parameters = parameters
    if route.app.dispatcher?
      recognized = [parameters.transform_keys(&:to_sym), nil]
    else
      response = route.app.serve(request)
      next if response[1][cascade_header] == "pass"

      recognized = [nil, response]
    end
    break
  end

  return recognized if recognized

  routing_error = Object.const_get(:ActionController).const_get(:RoutingError)
  raise routing_error, "No route matches #{env.fetch("PATH_INFO", "/").inspect}"
end

#recognize_route(env) ⇒ Object

Parameters:

  • env (Hash[String, untyped])

Returns:

  • (Object)


278
279
280
281
282
283
284
285
286
287
288
# File 'lib/torikago/engine_container.rb', line 278

def recognize_route(env)
  engine = resolve_runtime_class("#{camelize(name.to_s)}::Engine")
  routes = engine.routes
  return recognize_rails_route(routes, env) if routes.respond_to?(:router) && Object.const_defined?(:ActionDispatch, false)

  route = routes.recognize_path(
    env.fetch("PATH_INFO", "/"),
    method: env.fetch("REQUEST_METHOD", "GET").downcase.to_sym
  )
  [route.transform_keys(&:to_sym), nil]
end

#resolve_public_api_class(class_name) ⇒ Object

Parameters:

  • class_name (String)

Returns:

  • (Object)


362
363
364
365
# File 'lib/torikago/engine_container.rb', line 362

def resolve_public_api_class(class_name)
  boot_runtime!
  resolve_runtime_class(class_name)
end

#resolve_runtime_class(class_name) ⇒ Object

Parameters:

  • class_name (String)

Returns:

  • (Object)


367
368
369
370
371
372
# File 'lib/torikago/engine_container.rb', line 367

def resolve_runtime_class(class_name)
  root = isolated_box_enabled? ? box : Object
  # const_get is evaluated inside the Box object when isolation is enabled,
  # which keeps module-owned constants out of the host Object namespace.
  class_name.split("::").reduce(root) { |context, segment| context.const_get(segment) }
end

#ruby_box_runtime_available?Boolean

Returns:

  • (Boolean)


594
595
596
# File 'lib/torikago/engine_container.rb', line 594

def ruby_box_runtime_available?
  ENV["RUBY_BOX"] == "1"
end

#runtime_filesArray[String]

Returns:

  • (Array[String])


374
375
376
377
378
379
380
381
382
383
384
# File 'lib/torikago/engine_container.rb', line 374

def runtime_files
  @runtime_files ||= if rails_engine?
                       rails_runtime_files
                     else
                       [
                         *library_files,
                         *gateway_model_files,
                         *Dir[public_api_root.join("**/*.rb").to_s].sort
                       ]
                     end
end

#setup_pathPathname?

Returns:

  • (Pathname, nil)


434
435
436
437
438
# File 'lib/torikago/engine_container.rb', line 434

def setup_path
  return unless setup

  module_root.join(setup)
end

#with_box_runtime_errorsvoid

This method returns an undefined value.



474
475
476
477
478
479
480
481
482
# File 'lib/torikago/engine_container.rb', line 474

def with_box_runtime_errors
  yield
rescue BoxUnavailableError
  raise
rescue StandardError => e
  raise unless ENV["RUBY_BOX"] == "1"

  raise BoxUnavailableError, "Ruby::Box is unavailable for module #{name}: #{e.message}"
end

#without_bundler_setup_envvoid

This method returns an undefined value.



727
728
729
730
731
732
733
734
735
# File 'lib/torikago/engine_container.rb', line 727

def without_bundler_setup_env
  if BUNDLER_SETUP_ENV_MUTEX.owned?
    without_bundler_setup_env_unsynchronized { yield }
  else
    BUNDLER_SETUP_ENV_MUTEX.synchronize do
      without_bundler_setup_env_unsynchronized { yield }
    end
  end
end

#without_bundler_setup_env_unsynchronizedvoid

This method returns an undefined value.



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'lib/torikago/engine_container.rb', line 737

def without_bundler_setup_env_unsynchronized
  rubyopt = ENV["RUBYOPT"]
  bundler_setup = ENV["BUNDLER_SETUP"]

  if rubyopt&.include?("bundler/setup")
    options = rubyopt.split.reject { |option| option.include?("bundler/setup") }
    if options.empty?
      ENV.delete("RUBYOPT")
    else
      ENV["RUBYOPT"] = options.join(" ")
    end
  end

  ENV.delete("BUNDLER_SETUP")

  yield
ensure
  if rubyopt
    ENV["RUBYOPT"] = rubyopt
  else
    ENV.delete("RUBYOPT")
  end

  if bundler_setup
    ENV["BUNDLER_SETUP"] = bundler_setup
  else
    ENV.delete("BUNDLER_SETUP")
  end
end