PieceHealth
PieceHealth

Reputation: 33

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?

Upvotes: 1

Views: 87

Answers (1)

B Seven
B Seven

Reputation: 45941

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.

Upvotes: 1

Related Questions