0

I have developed a normal browser-based Rails game application. I'm now adding CloudMailin to the mix, effectively exposing an alternative interface via email.

Consider, as a representative example, my existing create action:

class GamesController < ApplicationController

  def create
    @game = Game.params[:new]

    if @game.random_create
      # Asked to create a game using random choices.
      # Make the random choices, then present it to the user for tweaking
      @game.expand_random_choices

      render :action => new
    else
      # Fully specified. Create the game
      begin
        @game.save!

        # ...other work including DB operations ...

        flash[:notice] += 'Game was successfully created.'
        redirect_to :action => :play, :id => @game
      rescue ActiveRecord::RecordInvalid
        @game.valid?
        render :action => 'new'
      end
    end
  end
end

I now have my PbemController for handling Cloudmailin emails:

class PbemController < ApplicationController

  # Handle inbound email
  def handle
    if email_is_a_game_creation
    ...
    end

    render :text => "Handled"
  end
end

What the best and DRYest way to invoke the existing create behaviour from the PbemController? Is my only real option extracting each "shared" action to a module in /lib' andinclude`ing that in each controller?

Chowlett
  • 45,935
  • 20
  • 116
  • 150

1 Answers1

1

Normally the best option is to move as much as you can into the model. That way any code that can be executed from the controller can also be executed from the handler.

You may be able to make a method like create_or_build_random that could potentially help here?

Steve Smith
  • 5,146
  • 1
  • 30
  • 31
  • Mm, I guess I do, maybe, have a bit too much in my controller. I'll see if I can do that. – Chowlett Aug 10 '11 at 15:13
  • Actually, no, on review the majority of the Game logic is in the Game model. The controller a) decides what to ask Game to do; b) handles Game reporting invalid parameters; c) handles linking up a new Game with a new Player for the session User; d) sets up flash; e) renders or redirects. It doesn't feel like any of that should be in the model. – Chowlett Aug 10 '11 at 15:44
  • To me it seems that if items shouldn't be in the model then you won't be duplicating within the mail handler from the controller but adding code specific to that mail handler in this place? – Steve Smith Aug 10 '11 at 16:37
  • Partially. The mail handler still has to create a new Player and link it to the Game, for instance; but it will indeed handle invalid parameters and "render" differently. – Chowlett Aug 11 '11 at 08:23
  • Accepted this answer because I think it's the correct tactic (although it's also what I've already largely got) - abstract as much into models as possible, then `lib/`ify what's left. – Chowlett Aug 11 '11 at 08:24