Skip to content

Commit

Permalink
Add Cascade
Browse files Browse the repository at this point in the history
this allows to have both Rails and Rage controllers in one application
  • Loading branch information
rsamoilov committed May 3, 2024
1 parent 078ab39 commit 830226c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
4 changes: 4 additions & 0 deletions lib/rage-rb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ def self.application
end
end

def self.multi_application
Rage::Router::Util::Cascade.new(application, Rails.application)
end

def self.routes
Rage::Router::DSL.new(__router)
end
Expand Down
14 changes: 10 additions & 4 deletions lib/rage/router/backend.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,18 @@ def on(method, path, handler, constraints: {}, defaults: nil)
raise "Invalid route handler format, expected to match the 'controller#action' pattern" unless handler =~ STRING_HANDLER_REGEXP

controller, action = Rage::Router::Util.path_to_class($1), $2
run_action_method_name = controller.__register_action(action.to_sym)

meta[:controller] = $1
meta[:action] = $2
if controller.ancestors.include?(RageController::API)
run_action_method_name = controller.__register_action(action.to_sym)

handler = eval("->(env, params) { #{controller}.new(env, params).#{run_action_method_name} }")
meta[:controller] = $1
meta[:action] = $2

handler = eval("->(env, params) { #{controller}.new(env, params).#{run_action_method_name} }")
else
# this is a Rails controller; notify `Rage::Router::Util::Cascade` to forward the request to Rails
handler = ->(_, _) { [404, { "X-Cascade" => "pass" }, []] }
end
else
raise "Non-string route handler should respond to `call`" unless handler.respond_to?(:call)
# while regular handlers are expected to be called with the `env` and `params` objects,
Expand Down
15 changes: 15 additions & 0 deletions lib/rage/router/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,19 @@ def path_to_name(str)
end
end
end

# @private
class Cascade
def initialize(rage_app, rails_app)
@rage_app = rage_app
@rails_app = rails_app
end

def call(env)
result = @rage_app.call(env)
return result if result[0] == :__http_defer__ || result[1]["X-Cascade".freeze] != "pass".freeze

@rails_app.call(env)
end
end
end

0 comments on commit 830226c

Please sign in to comment.