简体   繁体   中英

How can I deprecate a route in a Sinatra app?

I'm writing a API mock server by Sinatra, it looks like below

require 'sinatra/base'

class APIMockServer < Sinatra::Base

  post '/mock' do
    _body = params[:body]
    _status = params[:status] || 200
    APIMockServer.send params[:method], params[:action] do
      body _body
      status _status
    end
    'success'
  end

  run! if app_file == $0

end

I send a post request to /mock , the Sinatra App will generate a route dynamically.

require 'restclient'

RestClient.post(
    '127.0.0.1:4567/mock',
    {
        action: '/sayhi',
        method: 'get',
        body: 'hello world'
    }
)

So far it works as expected, but when I send another post request with same action , it doesn't take effect.

require 'restclient'

RestClient.post(
    '127.0.0.1:4567/mock',
    {
        action: '/sayhi',
        method: 'get',
        body: 'hello world, hello Sinatra' # the body is changing
    }
)

I guess because I defined two routes with same name, so the Sinatra take the first matched one to response. How can I deprecate the first one, so that the last one could take effect?

That is an interesting app. It's a metaprogramming API.

I think the issue is that once the route is defined, it is not being redefined.

So, perhaps you need to remove the route using something like

remove_method params[:method]

or

APIMockServer.remove_method params[:method], params[:action]

I'm not sure how Sinatra manages the defined routes, but you may want to look into that. Perhaps How do you remove a route from Sinatra? would be of some help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM