2016-12-06 118 views
0

我有一个要求,其中用户可以在该格式通过URL:葡萄与动态路由

http:site.com/[action]/[subject]?[option]=[value]

例如所有的下面是有效的网址:

http://example.com/trigger/a/b/c 
http://example.com/trigger/a 
http://example.com/trigger/a/b?something=value 
http://example.com/trigger/any/thing/goes/here 

我有grape资源是这样的:

class Test < Grape::API 
    params do 
    optional :option, type: String 
    end 

    get '/trigger/:a/:b/:c' do 
    { 
     type: 'trigger', 
     a: params[:a], 
     b: params[:b], 
     c: params[:c], 
     option: params[:option] 
    } 
    end 
end 

所以,如果我访问http://example.com/1/2/3/option=something那么我会得到

{ 
    "type": "trigger", 
    "a": "1", 
    "b": "2", 
    "c": "3", 
    "option": "something" 
} 

预期的行为:

使用应可在/trigger/

http://example.com/any/thing/goes/here/1/2/3?other=value&goes=here 

更新提供什么:

我发现这个解决方案(How do we identify parameters in a dynamic URL?)对于rails路线,我想要在grape中的这种行为。

感谢

回答

0

嗯,其实我一直在寻找wildcardsmatching params

get "trigger/*subject" do 
    { 
    params: params[:subject] 
    } 
end 

现在它将会像路径回应:

curl http://example.com/trigger/subject/can/be/anything 

输出:

{ 
params: "subject/can/be/anything" 
} 

感谢Neil的回答 Wildcard route in Grape