Created
January 22, 2014 08:40
-
-
Save sharnik/8555400 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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