Commit ca077fb9

mo khan <mo@mokhan.ca>
2014-05-31 15:25:02
add handler to process photo in background.
1 parent ae0b2ea
Changed files (5)
app
controllers
models
services
application
config
initializers
spec
services
application
app/controllers/my/photos_controller.rb
@@ -2,10 +2,10 @@ module My
   class PhotosController < BaseController
     before_filter :find_creation
 
-    #def initialize(mapper = PhotoToJQJsonMapper.new)
-      #@mapper = mapper
-      #super()
-    #end
+    def initialize(mapper = PhotoToJQJsonMapper.new)
+      @mapper = mapper
+      super()
+    end
 
     def index
       @photos = @cake.photos
app/models/photo.rb
@@ -10,6 +10,7 @@ class Photo < ActiveRecord::Base
   end
 
   def watermark
+    return '' if creation.nil?
     creation.watermark
   end
 
app/services/application/handlers/process_photo.rb
@@ -0,0 +1,17 @@
+class ProcessPhoto
+  def initialize(photos = Photo)
+    @photos = photos
+  end
+
+  def handles?(event)
+    :upload_photo == event
+  end
+
+  def handle(message)
+    photo = @photos.find(message[:photo_id])
+    photo.image = File.open(message[:file_path])
+    #photo.content_type = message[:content_type]
+    #photo.original_filename = message[:original_filename]
+    photo.save!
+  end
+end
config/initializers/container.rb
@@ -1,6 +1,8 @@
 container = Spank::Container.new
 container.register(:configuration) { EnvironmentVariables.new }
+
 container.register(:message_handler) { |builder| builder.build(PublishCakeToTwitter) }
+container.register(:message_handler) { |builder| builder.build(ProccessPhoto) }
 
 container.register(:queue) { |c| Delayed::Job }
 container.register(:message_bus) { |c| c.build(MessageBus) }.as_singleton
spec/services/application/handlers/process_photo_spec.rb
@@ -0,0 +1,33 @@
+require "spec_helper"
+
+describe ProcessPhoto do
+  let(:photos) { double }
+  subject { ProcessPhoto.new(photos) }
+
+  describe "#handles?" do
+    it "handles photo uploads" do
+      subject.handles?(:upload_photo).should be_true
+    end
+  end
+
+  describe "#handle" do
+    let(:image_path) { File.join(Rails.root, 'spec/fixtures/images/example.png') }
+    let(:photo) { Photo.new(id: rand(100)) }
+
+    before :each do
+      photos.stub(:find).with(photo.id).and_return(photo)
+    end
+
+    it "saves the uploaded image" do
+      message = {
+        photo_id: photo.id,
+        file_path: image_path,
+        content_type: 'image/jpeg',
+        original_filename: 'blah.jpg'
+      }
+      subject.handle(message)
+      photo.image.should_not be_nil
+    end
+  end
+end
+