How do you remove a route from Sinatra?

对着背影说爱祢 提交于 2020-01-04 03:14:04

问题


I have some dynamically loaded plugins which register their routes when they start up, however I also need to be able to remove their routes when they are disabled. Is there a way to remove existing routes?

The API didn't have any methods I could find to remove them, and the only other way I could think to do it would be to go right to the @routes object in Sinatra::Base, but I am not sure if you can do anything to that, and if you can... is it safe to do?


回答1:


Looking through the code for a few minutes I do not see any code that 'destructively' mutates the routes other than:

C:\Ruby\lib\ruby\gems\1.9.1\gems\sinatra-1.3.1\lib\sinatra\base.rb:
  936        def reset!
  937          @conditions     = []
  938:         @routes         = {}
  939          @filters        = {:before => [], :after => []}
  940          @errors         = {}

This is a 'nuke it from orbit' approach, and presumably not what you need. Based on this investigation, I think you will need to modify the routes hash yourself.

For the current version of code, this looks 'safe' to me, insofar as the route! method always looks up the current array of routes and iterates them normally (there is no caching):

def route!(base = settings, pass_block=nil)
  if routes = base.routes[@request.request_method]
    routes.each do |pattern, keys, conditions, block|
      pass_block = process_route(pattern, keys, conditions) do |*args|
        route_eval { block[*args] }
      end
    end
  end

  # Run routes defined in superclass.
  if base.superclass.respond_to?(:routes)
    return route!(base.superclass, pass_block)
  end

  route_eval(&pass_block) if pass_block
  route_missing
end

The internals of Sinatra around storing routes have shifted in recent releases, so I wouldn't rely on this always working without testing with each new release. Better yet, propose a patch and see if you can get the functionality accepted incorporated into the main library.




回答2:


May be you condider this approach,

before '/the_path_you_want_to_remove' do
   redirect '/the_path_is_default_page_or_someting'
end

You could put this before action for overriding the route you want to remove, so the route is not be accessed and implemented.

If you want to enable that route again, just delete the before action.

Or remove the item in array disable_routes

before do
    disable_routes = ['/test', '/test/*', '/test*']
    redirect '/default_page' if disable_routes.include?(request.path_info)
end



回答3:


You could prevent the route from returning anything by setting an after block.



来源:https://stackoverflow.com/questions/8212778/how-do-you-remove-a-route-from-sinatra

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