Sonntag, 23. März 2014

Reduce the routes! ... have as less as required

If your Ruby on Rails application contains too much routes, you should reduce them. For example this routes.rb (taken from my previous post Simple RESTful Ruby on Rails routes):
resources :people
offers those routes (doing rake routes in the Rails console):
people GET /people(.:format) people#index
POST /people(.:format) people#create
new_person GET /people/new(.:format) people#new
edit_person GET /people/:id/edit(.:format) people#edit
person GET /people/:id(.:format) people#show
PUT /people/:id(.:format) people#update
DELETE /people/:id(.:format) people#destroy
But if the people_controller.rb looks like:
class PeopleController < ApplicationController
  def index # GET
  end

  def show # GET
  end
end

there are 5 routes too much. Offering them anyway is misleading and improper.
Those would be sufficient:

people GET /people(.:format) people#index
person GET /people/:id(.:format) people#show
That is why the routing generator 'resources' has the option :only: And it is easy to achieve. Refactoring the routes.rb to:
resources :people, :only => [:index, :show]
generates the 2 required routes to PeopleController#index and PeopleController#show.
Just to mention it, the opposite to :only is :except.
For example:
resources :people, :except => :destroy
offers all standard RESTful routes to the people resources except 'destroy':
people GET /people(.:format) people#index
POST /people(.:format) people#create
new_person GET /people/new(.:format) people#new
edit_person GET /people/:id/edit(.:format) people#edit
person GET /people/:id(.:format) people#show
PUT /people/:id(.:format) people#update
Offering routes to a resource and not having the appropriate actions in stock is malicious.
Reduce them to the required amount!

Supported by Ruby 2.1.1 and Ruby on Rails 3.2.17

Keine Kommentare:

Kommentar veröffentlichen