我正在开发一个游戏应用程序(移动前端,Rails后端),并试图决定是否应该严格使用RESTful.如果我这样做,我似乎会创造更多的控制器.例如,我需要实现几个游戏操作,如攻击,防御等.如果我严格遵守RESTful,我将需要为每个游戏操作创建一个控制器,只需一个REST操作(更新).如果我去非RESTul并且创建了一个通用的战斗控制器,那么我就可以为攻击,防御等创建方法/动作.看起来更加麻烦,严格来说是RESTful.
任何见解将不胜感激.
攻击,防守等都属于同一种资源:Action
.
例如:
PUT actions/attack # to attack PUT actions/defend # to defend GET actions # to get the list of all available actions
要实现这个作为REST,我会这样:
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
这只是为了大致了解如何做得好.