Redirect Sinatra request changing method and body

泄露秘密 提交于 2019-12-12 03:55:27

问题


Is there a way to handle a GET request on Sinatra and make a PATCH request with a different body on the same server? User makes a request GET /clean_beautiful_api and server redirects it to PATCH /dirty/clogged_api_url_1?crap=2 "{request_body: 1}"?

I want to clean up legacy API without interfering with the functionality.


回答1:


If I've understood correctly, the easiest way is to extract the block used for the patch into a helper:

patch "/dirty/clogged_api_url_1"
  crap= params[:crap]
end

to:

helpers do
  def patch_instead( params={} )
    # whatever you want to do in here
    crap= params[:crap]
  end
end

get "/clean_beautiful_api" do
  patch_instead( params.merge(request_body: 1) )
end


patch "/dirty/clogged_api_url_1"
  patch_instead( params )
end

Or you could use a lambda…

Patch_instead = ->( params={} ) {
  # whatever you want to do in here
  crap= params[:crap]
}

get "/clean_beautiful_api" do
  Patch_instead.call( params.merge(request_body: 1) )
end

# you get the picture

the main thing is to extract the method to somewhere else and then call it.


Edit: You can also trigger another route internally using the Rack interface via call.



来源:https://stackoverflow.com/questions/15500759/redirect-sinatra-request-changing-method-and-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!