ruby-on-rails – 如何在routes.rb中创建自定义路由助手

我的路线中有几个重现的模式,我想通过创建一个为我创建这些路径的方法来使其成为干.

我想要完成的一个例子可以在Devise gem中看到,您可以使用以下语法:

#routes.rb
devise_for :users

这将产生Devise所需的所有路线.我想创造类似的东西.例如说我有以下路线:

resources :posts do
  member do
    get 'new_file'
    post 'add_file'
  end
  match 'files/:id' => 'posts#destroy_file',:via => :delete,:as => :destroy_file
end

resources :articles do
  member do
    get 'new_file'
    post 'add_file'
  end
  match 'files/:id' => 'articles#destroy_file',:as => :destroy_file
end

这开始变得凌乱很快,所以我想找到一种方式来做到这一点:

resources_with_files :posts
resources_with_files :articles

所以我的问题是,如何创建resources_with_files方法

解决方法

把它放在像lib / routes_helper.rb这样的东西:
class Actiondispatch::Routing::Mapper
  def resources_with_files(*resources)
    resources.each do |r|
      Rails.application.routes.draw do
        resources r do
          member do
            get 'new_file'
            post 'add_file'
            delete 'files' => :destroy_file
          end
        end
      end
    end
  end
end

并在config / routes.rb中要求它

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...