如何添加可用于Gem路由的方法?

时间:2015-02-12 05:13:14

标签: ruby-on-rails routes gem

我正在为Rails构建一个gem,并希望为使用我的gem的Rails应用程序的路由提供一个方法。

基本上,我希望使用我的宝石的人能够说出

websockets_for :messages

将为他们创建一堆路线。我不确定在哪里定义该方法,以便它在路径文件中可用。

该方法如下所示:

def websockets_for(resources)
  get "/#{resources}", to: "#{resources}#index", as: resources
end

它基本上是我想要用来生成路线的辅助方法。

我只找到了这个:https://www.pgrs.net/2007/09/28/add-routes-with-a-rails-plugin-or-gem/

看起来很旧(从2007年开始),我认为ActionController::Routing仍在使用中。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

根据Frederick Cheung的评论,我能够实现这一点:

require 'action_dispatch/routing'
require 'active_support/concern'

module ActionDispatch::Routing
  class Mapper
    def websockets_for(resource, &block)
      # here, use methods like get, match, etc
      get "/#{resources}", to: "#{resources}#index", as: resources
    end
  end
end

有效!现在,如果安装了gem,则可以在Rails应用程序的路径中使用方法websockets_for