Created
August 15, 2011 09:37
-
-
Save mindscratch/1145962 to your computer and use it in GitHub Desktop.
Rails: simple resource routes generation (rails 3.0)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ActionDispatch | |
| module Routing | |
| class Mapper | |
| # resources can be one or more resource types (should be plural) | |
| # | |
| # ex: simple_resources :widgets | |
| # | |
| # This will generate the following routes: | |
| # | |
| # GET widgets => widgets#index | |
| # GET widget/:id => widgets#show | |
| # PUT widget/:id => widgets#update | |
| # DELETE widget/:id => widgets#destroy | |
| # POST widget => widgets#create | |
| def simple_resources(*resources) | |
| resources.each do |resource| | |
| multi_resource = resource.to_s | |
| single_resource = multi_resource.singularize | |
| controller = multi_resource | |
| get multi_resource, :to => "#{controller}#index" | |
| get "#{single_resource}/:id", :to => "#{controller}#show" | |
| put "#{single_resource}/:id", :to => "#{controller}#update" | |
| delete "#{single_resource}/:id", :to => "#{controller}#destroy" | |
| post "#{single_resource}", :to => "#{controller}#create" | |
| end | |
| self | |
| end | |
| # another version, assumes resource is singular | |
| # ex: simple_resource :widget | |
| def simple_resource(*resource, &blk) | |
| default_params = [*resource] | |
| resources(*default_params, &blk) | |
| domain = resource[0].to_s.singularize | |
| get "/#{domain.pluralize}", :to => "#{domain}#index" | |
| self | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment