Skip to content

Instantly share code, notes, and snippets.

@sharnik
Created January 22, 2014 08:40
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 sharnik/8555400 to your computer and use it in GitHub Desktop.
Save sharnik/8555400 to your computer and use it in GitHub Desktop.
require 'spec_helper'
describe Users do
describe 'Update user' do
let(:user) { FactoryGirl.create(:user) }
let(:image) {
Rack::Test::UploadedFile.new('spec/fixtures/images/treme.jpg', 'image/jpeg')
}
before do
post "/api/users/#{user.id}", {
avatar: {
:content_type => image.content_type,
:filename => image.original_filename,
:file_data => Base64.encode64(image.read)
}
}.to_json, "Content-Type" => "application/json"
end
it 'returns avatar URL' do
JSON.parse(response.body)['avatar_url'].should_not be_nil
end
end
end
class UserUpdateService
def initialize(user, params)
@user = user
@params = params
end
def process
@params[:avatar] = parse_image_data(@params[:avatar]) if @params[:avatar]
@user.update!(@params)
ensure
clean_tempfile
end
private
def parse_image_data(image_data)
@tempfile = Tempfile.new('user-avatar')
@tempfile.binmode
@tempfile.write Base64.decode64(image_data[:file_data])
@tempfile.rewind
ActionDispatch::Http::UploadedFile.new(
:tempfile => @tempfile,
:content_type => image_data[:content_type],
:filename => image_data[:filename]
)
end
def clean_tempfile
if @tempfile
@tempfile.close
@tempfile.unlink
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment