Commit 121c49fd

mo khan <mo@mokhan.ca>
2014-05-14 03:45:03
extract update cake command.
1 parent 19e8012
Changed files (3)
app/controllers/creations_controller.rb
@@ -8,7 +8,6 @@ class CreationsController < ApplicationController
 
   def show
     @creation = FindCreationQuery.new.fetch(params[:id])
-    @primary_photo = @creation.primary_image
     expires_in(1.minute) unless user_signed_in?
   end
 
@@ -37,22 +36,23 @@ class CreationsController < ApplicationController
   end
 
   def update
-    @creation = current_user.creations.find(params[:id])
-    @creation.categories.clear
-    @creation.categories << Category.find(params[:category_id]) if params[:category_id]
-    current_user.tag(@creation, :with => params[:creation_tags], :on => :tags)
+    UpdateCakeCommand.new(self).run(params[:id], params[:category_id], params[:creation_tags], creation_params)
+  end
+
+  def update_cake_succeeded(cake)
+    @creation = cake
+    redirect_to new_creation_photo_url(@creation)
+  end
 
-    if @creation.update_attributes(creation_params)
-      redirect_to new_creation_photo_url(@creation)
-    else
-      flash[:error] = @creation.errors.full_messages
-      render :edit
-    end
+  def update_cake_failed(cake)
+    @creation = cake
+    flash[:error] = @creation.errors.full_messages
+    render :edit
   end
 
   def destroy
     current_user.creations.find(params[:id]).destroy
-    redirect_to(creations_url) 
+    redirect_to(creations_url)
   end
 
   def mine
app/services/update_cake_command.rb
@@ -0,0 +1,20 @@
+class UpdateCakeCommand
+  def initialize(context)
+    @context = context
+  end
+
+  def run(id, category_id, creation_tags, creation_params)
+    current_user = @context.current_user
+
+    creation = current_user.creations.find(id)
+    creation.categories.clear
+    creation.categories << Category.find(category_id) if category_id
+    current_user.tag(creation, with: creation_tags, on: :tags)
+
+    if creation.update_attributes(creation_params)
+      @context.update_cake_succeeded(creation)
+    else
+      @context.update_cake_failed(creation)
+    end
+  end
+end
app/views/creations/show.html.erb
@@ -31,7 +31,7 @@
 
 <div class="row">
   <div class="span6">
-    <img class="thumbnail" src="<%= @primary_photo.image.large.url %>" alt="<%= @creation.name %>" />
+    <img class="thumbnail" src="<%= @creation.primary_image.image.large.url %>" alt="<%= @creation.name %>" />
   </div>
   <div class="span6">
     <h1><%= link_to @creation.name, creation_path(@creation) %></h1>