Skip to content

Instantly share code, notes, and snippets.

@soulcutter
Forked from jeshuaborges/photo_claimer.rb
Created November 27, 2012 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soulcutter/4156730 to your computer and use it in GitHub Desktop.
Save soulcutter/4156730 to your computer and use it in GitHub Desktop.
require_relative './upload_store'
class PhotoClaimer
attr_writer :photo_source
attr_writer :upload_storage_source
class FileNotFound < RuntimeError; end
def initialize(user_id, file_name)
@user_id = user_id
@file_name = file_name
end
# Public: Do it!
#
# Returns a Photo instance.
def claim
photo_source.call(user_id: @user_id).tap do |photo|
# parent model must have identity before saving because the id
# is used for the file path.
begin
photo.file_data = tempfile # move `photo.file.store!(tempfile)` into Photo#store_file!
photo.save!
rescue Exception => e
photo.destroy
# logging?
raise e
end
end
end
private
def photo_source
@photo_source ||= Photo.public_method(:create!)
end
def upload_storage_source
@upload_storage_source ||= UploadStore.public_method(:get)
end
def tempfile
tmp = Tempfile.new(@file_name)
stage_file do |file|
tmp.write(file.body)
end
tmp.rewind
tmp
end
# Internal: Find the associated uploaded file.
#
# Returns: Fog::File instance.
# Raises FileNotFound error when file cannot be located.
def stage_file(&block)
file = upload_storage_source.call(@file_name)
raise FileNotFound, "#{@file_name} not found" unless file
begin
block.call(file)
ensure
file.destroy
end
end
end
require_relative '../../app/models/photo_claimer'
describe PhotoClaimer do
let(:claimer) { PhotoClaimer.new(1, 'some/path.jpeg') }
before do
stub_const('Tempfile', double(:tempfile_class).as_null_object)
claimer.photo_source = ->(*) { double(:photo).as_null_object }
claimer.upload_storage_source = ->(*) { double(:uploadstore_class).as_null_object }
end
it 'errors when file cannot be found' do
claimer.upload_storage_source = ->(*) { nil }
expect{ claimer.claim }.to raise_error(PhotoClaimer::FileNotFound)
end
it 'deletes the uploaded file' do
file = double(:file).as_null_object
claimer.upload_storage_source = ->(*) { file }
file.should_receive(:destroy)
claimer.claim
end
it 'creates a photo record' do
claimer.claim.should be
end
it 'assigns attaches uploaded file' do
tempfile = double(:tempfile).as_null_object
Tempfile.stub(:new) { tempfile }
photo = double(:photo)
photo.should_receive(:file_data=).with(tempfile)
photo.should_receive(:save!)
claimer.photo_source = ->(*) { photo }
claimer.claim
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment