开发者

How can I create custom route helpers for usage in routes.rb

开发者 https://www.devze.com 2023-03-13 13:10 出处:网络
I have a few reoccurring patterns in my routes.rb and I would like to make it DRY by creating a method that creates those routes for me.

I have a few reoccurring patterns in my routes.rb and I would like to make it DRY by creating a method that creates those routes for me.

An example of what I want to accomplish can be seen in the Devise gem where you can use the following syntax:

#routes.rb
devise_for :users

Which will generate all the routes necessary for Devise. I would like to create something similar. Say for example that I have the following routes:

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', :via => :delete, :as => :destroy_file
end

This starts getting messy quite quickly so I would like to find a way to do it like this instead:

resources_with_files :posts
resources_with_files :articles

So my question is, how can I create the resources_with_files method?


Put this in something like 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

and require it in config/routes.rb

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号