views:

71

answers:

1

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.

+6  A: 

Think about it. 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.

glebm
Thanks, that makes sense although technically, there isn't a need for the usual Rails REST actions because there isn't an actions model, they are hardcoded. However, each action will result in changes to other models. Essentially I would create an actions controller and if I want to go RESTful, create custom REST actions. However, it seems that I shouldn't use REST in this case and simply create a controller for all the different actions, thoughts?
Bob
I've updated my answer. Storing them like this makes things like action security clearance levels trivial to implement, among other things :)
glebm
Thanks, it's a creative solution though it seems simpler to just implement custom REST actions.
Bob