Method: CmisServer.mount_engine

Defined in:
lib/cmis_server.rb

.mount_engine(application, mount_path, mount_name: nil, debug: false) ⇒ Object

Method to properly mount CmisServer in a Rails application Usage in host app: CmisServer.mount_engine(Rails.application, “/path”, mount_name: ‘custom_name’)



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/cmis_server.rb', line 45

def self.mount_engine(application, mount_path, mount_name: nil, debug: false)
  if application && application.routes && mount_path
    # Save original Rails.application
    original_rails_app = Rails.application
    Rails.application = application
    
    # Make sure engine routes are loaded first
    if !EngineDiagnostics.routes_loaded?
      EngineDiagnostics.reload_engine_routes!
      
      # Log diagnostic if in debug mode
      if debug
        puts "CMIS Server Engine Diagnostics:"
        puts EngineDiagnostics.diagnostic_info.inspect
      end
    end
    
    # Check if application is already initialized
    if !application.initialized?
      puts "CMIS Server: Initializing application before mounting" if debug
      # Handle Rails 7+ with frozen arrays in autoload paths
      begin
        application.initialize!
      rescue FrozenError => e
        puts "CMIS Server: Frozen array error during initialization (Rails 7+ issue)" if debug
        puts "CMIS Server: Proceeding with mounting anyway" if debug
      end
    end
    
    # Mount the engine with a custom name if provided
    application.routes.draw do
      if mount_name
        mount CmisServer::Engine => mount_path, as: mount_name
      else
        mount CmisServer::Engine => mount_path
      end
    end
    
    # Force route drawing
    application.routes.finalize!
    
    # Check if engine routes are loaded again
    engine_routes_count = Engine.routes.routes.size
    if engine_routes_count == 0
      puts "CMIS Server: Engine routes not loaded, forcing reload again" if debug
      
      # Try once more to reload engine routes
      EngineDiagnostics.reload_engine_routes!
      
      # And refresh application routes
      application.routes.reload!
    end
    
    # Count mounted routes for verification
    cmis_routes = application.routes.routes.select do |route|
      route.path.spec.to_s.include?(mount_path) || 
      (route.defaults[:controller]&.start_with?('cmis_server'))
    end
    
    puts "CMIS Server mounted at '#{mount_path}' with #{cmis_routes.size} routes" if debug
    
    # Restore the original Rails.application
    Rails.application = original_rails_app
    
    return cmis_routes.size
  else
    puts "CMIS Server mount failed: Invalid parameters" if debug
    return 0
  end
end