Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default :exclude option for Rails resource routing

A minor question:

I am using Rails for my REST API, but since it is a RESTful API I don't really need :new or :edit routes for any of my resources since people will only be interacting with this API entirely through automated JSON requests, not graphically. There's no need for a dedicated edit page, for instance.

Currently, I need to do something like this for every resource defined:

# routes.rb
resources :people, except: [:new, :edit]

It's not a big deal to have :except options on every resource in /config/routes.rb, but is there a way to define defaults so I don't have to specify this on every resource? I'd like to DRY up this code a bit, without doing something lame like passing around a local variable with default options everywhere.

More generally, can you set default options for Rails routes to follow aside from :exclude?

Thanks!

like image 312
osdiab Avatar asked Oct 28 '14 18:10

osdiab


2 Answers

with_options for a rescue!

with_options(except: [:new, :edit]) do |opt|
  opt.resource :session
  opt.resource :another_resource
  opt.resources :people
end
like image 188
BroiSatse Avatar answered Oct 20 '22 23:10

BroiSatse


You can define a custom method to draw your routes under ActionDispatch::Routing::Mapper namespace. In your routes.rb file, on top of the file before Rails.application.routes.draw do :

class ActionDispatch::Routing::Mapper

  def draw(resource)
    resources resource, except: [:new, :edit]
  end

end

#routes start here
Rails.application.routes.draw do

  draw :people
  draw :products
  # ...rest of the routes

end

Now for those particular resources you can call the draw method as above.

like image 20
Alireza Avatar answered Oct 20 '22 23:10

Alireza