如何添加可以在路由中使用的方法到Gem?
How to add method that can be used in routes to Gem?
我正在为 Rails 构建一个 gem,并希望为使用我的 gem 的 Rails 应用程序的路由提供一个方法。
基本上,我希望使用我的 gem 的人能够说
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
仍在使用。执行此操作的最佳方法是什么?
根据 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,方法 websockets_for
可用于 Rails 应用程序的路由。
我正在为 Rails 构建一个 gem,并希望为使用我的 gem 的 Rails 应用程序的路由提供一个方法。
基本上,我希望使用我的 gem 的人能够说
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
仍在使用。执行此操作的最佳方法是什么?
根据 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,方法 websockets_for
可用于 Rails 应用程序的路由。