2016-12-06 135 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