Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 679
DanneManne Avatar asked Jun 16 '11 03:06

DanneManne


1 Answers

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

like image 50
chrismealy Avatar answered Oct 23 '22 17:10

chrismealy