Going strictly RESTful on Rails
I'm working on a gaming app (mobile front ends, Rails backend) and trying to decide if I should go strictly RESTful. It appears that I'll be creating a lot more controllers if I do so. For example, there are several game actions I need to implement like attack, defend, etc. If开发者_如何转开发 I go strictly RESTful, I'll need to create a controller for each game action with only one REST action (update). If I go non-RESTul and creates say a generic battle controller, I can then create methods/actions for attack, defend, etc. Seems like more hassle to go strictly RESTful.
Any insights will be much appreciated.
Attack, defend, etc are all of the same kind of resource: Action
.
E.g.:
PUT actions/attack # to attack
PUT actions/defend # to defend
GET actions # to get the list of all available actions
To implement this as REST, I'd go something like this:
class PlayerActionsController ...
def index
@actions = PlayerAction.all
respond_with @actions
end
def update
@action = PlayerAction.find(params[:id])
respond_with @action.perform(params)
end
end
class GenericAction
attr_readable :name
def initialize(name)
@name = name
end
def perform(arguments)
self.send(name, arguments) if self.class.find(name)
end
ACTIONS = []
ACTIONS_BY_NAME = {}
class << self
def add_action(*names)
names.each do |name|
action = Action.new(name)
ACTIONS_BY_NAME[name] = action
ACTIONS << action
end
end
def index
ACTIONS.dup
end
def find(name)
ACTIONS_BY_NAME[name]
end
end
def
class PlayerAction < GenericAction
add_action :attack, :defend
def attack(params)
player, target = Player.find(params[:player_id]), Player.find(params[:target_id])
...
end
def defend(params)
...
end
end
This is just to give a rough idea of how it could be done well.
精彩评论