删除Gem中指定的路由?

时间:2011-05-05 02:13:17

标签: ruby-on-rails ruby-on-rails-3 rubygems routes override

有没有办法删除Rails 3中gem中指定的路由?异常记录器gem指定了我不想要的路由。我需要在路由上指定约束,如:

scope :constraints => {:subdomain => 'secure',  :protocol => 'https'} do 
    collection do
        post :query
        post :destroy_all
        get :feed
    end
end

根据Rails Engine docs,我想我可以创建一个猴子补丁并添加一个没有指定路径的路由文件[“config / routes”]。paths数组但文件没有被添加到ExceptionLogger :: Engine.paths [“config / routes”]。paths

File: config/initializers/exception_logger_hacks.rb

ExceptionLogger::Engine.paths["config/routes"].paths.unshift(File.expand_path(File.join(File.dirname(__FILE__), "exception_logger_routes.rb")))

我离开基地吗?也许有更好的方法可以做到这一点?

2 个答案:

答案 0 :(得分:9)

可以防止Rails加载特定gem的路由,这样就不会添加任何gem路由,所以你必须手动添加你想要的路径:

在application.rb中添加一个初始化程序,如下所示:

class Application < Rails::Application
...
initializer "myinitializer", :after => "add_routing_paths" do |app|
  app.routes_reloader.paths.delete_if{ |path| path.include?("NAME_OF_GEM_GOES_HERE") }
end

答案 1 :(得分:2)

这是一种对我有用的方式。

它不会“删除”路线,但可让您控制它们匹配的位置。您可能希望请求的每条路线都匹配某些东西,即使它是底部的全部404。

首先加载您的应用程序路由(MyApp / config / routes.rb)(除非您修改了默认加载过程)。首先匹配的路线优先。

因此,您可以重新定义要明确阻止的路由,或者使用YourApp / config / routes.rb文件底部的catch all路径阻止它们。

不幸的是,命名路线似乎遵循了ruby的“最后定义胜利”规则。因此,如果路由已命名且您的应用或引擎使用这些名称,则需要首先定义路由(因此首先匹配)和最后路径(所以命名路由按预期方式指向,而不是引擎定义。)< / p>

要在引擎添加后重新定义引擎的路由,请创建一个名为

的文件
# config/named_routes_overrides.rb
Rails.application.routes.draw do
  # put your named routes here, which you also included in config/routes.rb
end

# config/application.rb
class Application < Rails::Application
  # ...

  initializer 'add named route overrides' do |app|
    app.routes_reloader.paths << File.expand_path('../named_routes_overrides.rb',__FILE__) 
    # this seems to cause these extra routes to be loaded last, so they will define named routes last.
  end
end

您可以在控制台中测试此路由三明治:

> Rails.application.routes.url_helpers.my_named_route_path
=> # before your fix, this will be the engine's named route, since it was defined last.

> Rails.application.routes.recognize_path("/route/you/want/to/stop/gem/from/controlling")
=> # before your fix, this will route to the controller and method you defined, rather than what the engine defined, because your route comes first.

修复后,这些调用应该相互匹配。

(我最初发布在炼油厂宝石谷歌小组这里:https://groups.google.com/forum/?fromgroups#!topic/refinery-cms/N5F-Insm9co