2014-10-04 65 views
0

考虑的config.ru以下小节:机架:映射更复杂的路线

run Rack::URLMap.new(                              
    "/" => Ramaze,                               
    "/apixxx" => MyGrapeAPI.new                                
) 

这工作。 (注意后缀xxx)。每个去/apixxx/*的请求都发送到Grape API端点,其他所有内容都由Ramaze应用程序提供。 (Ramaze建立在机架上。)

但是,我真的想要做的是地图/api而不是/apixxx。但是,Ramaze应用程序碰巧有/api/v1/*下的端点。我想要的是将/api以下的所有不在/api/v1之下的请求都发送到Grape API(例如/api/somethingelse),并且每个/api/v1/*请求都转到Ramaze。

我已经尝试在URLMap中使用Regexps而不是字符串,但这不起作用。我尝试过URLMap和Rack :: Cascade的组合,并没有成功。

最理想的是,如果我可以使用正则表达式映射,或者如果我可以使用一块代码来映射,我会参加比赛。

回答

0

这里是我结束了使用,这要归功于从@rekado尖端。

# config.ru 

class APIRoutingAdapter 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    request = Rack::Request.new(env) 
    # Version 1 of the API was served from Ramaze, but the API has since been 
    # moved out of Ramaze. 
    if request.path =~ %r{/api/(?!v1)} 
     # Have the Grape API handle the request 
     env_without_api_prefix = env.dup 
     ['REQUEST_PATH', 'PATH_INFO', 'REQUEST_URI'].each do |key| 
     env_without_api_prefix[key] = env_without_api_prefix[key].gsub(%r{^/api}, '') 
     end 

     TheGrapeAPI.new.call(env_without_api_prefix) 
    else 
     # Let Ramaze handle the request 
     @app.call(env) 
    end 
    end 
end 

use APIRoutingAdapter 

run Ramaze