Commit 75d7617a
Changed files (3)
app
controllers
api
services
application
infrastructure
app/controllers/api/v1/photos_controller.rb
@@ -10,7 +10,8 @@ module Api
end
def create
- @photo = UploadPhoto.new.run(params[:cake_id], params)
+ cake = current_user.creations.find(params[:cake_id])
+ @photo = UploadPhoto.new(cake).run(params)
end
end
end
app/services/application/upload_photo.rb
@@ -1,28 +1,28 @@
class UploadPhoto
- def initialize(cakes = Creation)
- @cakes = cakes
+ attr_reader :cake, :storage
+
+ def initialize(cake)
+ @cake = cake
+ @storage = TemporaryStorage.new
end
- def run(cake_id, params)
- ActiveRecord::Base.transaction do
- photo = @cakes.find(cake_id).photos.create!(image_processing: true, watermark: params[:watermark])
- tempfile = move_to_temporary_storage(params[:image].path, params[:image].original_filename)
- ProcessPhotoJob.perform_later(photo, tempfile)
- photo
+ def run(params)
+ with_transaction do
+ create_photo!(params[:watermark]) do |photo|
+ ProcessPhotoJob.perform_later(photo, storage.store(params[:image]))
+ end
end
end
private
- def move_to_temporary_storage(temp_file_path, original_filename)
- new_path = "#{create_tmp_dir}/#{original_filename}"
- FileUtils.mv(temp_file_path, new_path)
- new_path
+ def with_transaction
+ ActiveRecord::Base.transaction do
+ yield
+ end
end
- def create_tmp_dir
- directory = Rails.root.join("tmp/uploads/#{SecureRandom.uuid}")
- system "mkdir -p #{directory}"
- directory
+ def create_photo!(watermark)
+ cake.photos.create!(image_processing: true, watermark: watermark)
end
end
app/services/infrastructure/temporary_storage.rb
@@ -0,0 +1,15 @@
+class TemporaryStorage
+ def store(file)
+ "#{tmp_dir}/#{file.original_filename}".tap do |new_path|
+ FileUtils.mv(file.path, new_path)
+ end
+ end
+
+ private
+
+ def tmp_dir
+ Rails.root.join("tmp/uploads/#{SecureRandom.uuid}").tap do |directory|
+ system "mkdir -p #{directory}"
+ end
+ end
+end