Created
June 12, 2010 03:58
-
-
Save shreeve/435404 to your computer and use it in GitHub Desktop.
This file contains 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
# RESTful API | |
# | |
# +--------+-------------------+---------+---------+----------+-----------+ | |
# | METHOD PATH | ACTION | PAYLOAD | TEMPLATE | REDIRECT | | |
# + -------+-------------------+---------+---------+----------+-----------| | |
# | GET | /orders | index | | index | | | |
# | GET | /orders/new | new | | edit | | | |
# | GET | /orders/4;edit | edit | | edit | | | |
# | GET | /orders/4 | show | | show | | | |
# + -------+-------------------+---------+---------+----------+-----------+ | |
# | POST | /orders | create | yes | | show/edit | | |
# | POST | /orders/4;update | update | yes | | show/edit | | |
# | POST | /orders/4;destroy | destroy | yes | | index | | |
# + -------+-------------------+---------+---------+----------+-----------+ | |
# | PUT | /orders/4 | update | yes | | show/edit | | |
# + -------+-------------------+---------+---------+----------+-----------+ | |
# | DELETE | /orders/4 | destroy | yes | | index | | |
# + -------+-------------------+---------+---------+----------+-----------+ | |
REST = %w[ index new edit show create update destroy ] | |
THEN = { | |
:create => :show, | |
:update => :show, | |
:destroy => :index, | |
} | |
def self.restful ; @restful = true; end | |
def self.restful?; @restful ; end | |
def rest(info = @info.first) | |
http = @env['REQUEST_METHOD'] | |
# determine which action to perform | |
@action = case http | |
when 'GET' | |
case info | |
when nil then :index | |
when 'new' then @info.shift; :new | |
when /(.);edit$/ then info.replace($`+$1); :edit | |
else REST.include?(info) || !respond_to?(info) ? :show : info | |
end | |
when 'POST' | |
case info | |
when nil then :create | |
when /(.);update$/ then info.replace($`+$1); :update | |
when /(.);destroy$/ then info.replace($`+$1); :destroy | |
else :create #!# raise "no nested resources" | |
end | |
when 'PUT' then :update if info | |
when 'DELETE' then :destroy if info | |
end | |
# perform the action or eject | |
if @action && respond_to?(@action) | |
@follow = THEN[@action] | |
send @action | |
else | |
eject | |
end | |
# determine how to follow the action (render or redirect) | |
case http | |
when 'GET' | |
send @follow if @follow | |
when 'POST', 'PUT', 'DELETE' | |
case @follow | |
when nil | |
when :index then redirect_to('', 303) | |
when :edit then redirect_to("#{@id};edit", 303) | |
when :show then redirect_to(@id, 303) | |
else respond_to?(@follow) ? send(@follow) : eject | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment