Skip to content

Instantly share code, notes, and snippets.

@solon
Created February 5, 2011 02:40
Show Gist options
  • Save solon/812148 to your computer and use it in GitHub Desktop.
Save solon/812148 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'sinatra'
require 'data_mapper'
require 'carrierwave'
require 'carrierwave/orm/datamapper'
ROOT = Dir.pwd
class ImageUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
nil #store files at root level
end
def cache_dir
"#{ROOT}/tmp/"
end
end
class Person
include DataMapper::Resource
property :id, Serial
property :name, String
# http://github.com/jnicklas/carrierwave/issues#issue/87/comment/396035
property :avatar, String, :length => 255, :auto_validation => false
mount_uploader :avatar, ImageUploader
# Override property setter to mark property as dirty
#
# Compare wprater's version (working):
# https://github.com/wprater/carrierwave/blob/datamapper_property_marked_dirty/lib/carrierwave/orm/datamapper.rb
#
# with master version (not working):
# https://github.com/jnicklas/carrierwave/blob/master/lib/carrierwave/orm/datamapper.rb
#
# Here's the relevant commit:
# https://github.com/wprater/carrierwave/commit/f0245a66df097e78ab3bb77b4c6eb3018123109d
#def avatar=(obj)
# self.attribute_set(:avatar, obj)
# _mounter(:avatar).cache(obj)
#end
end
DataMapper::setup(:default, "sqlite3::memory:")
DataMapper.auto_migrate!
first_person = Person.new(:name => 'Alice')
if first_person.save
puts "person saved successfully"
else
first_person.errors.each do |e|
puts e
end
end
get '/' do
erb :edit
end
post '/update' do
person = Person.get(1)
puts "POST /update"
puts "params = #{params.inspect}"
if person.update(params[:person])
redirect '/'
else
person.errors.each do |e|
puts e
end
end
end
__END__
@@ edit
<h1>Carrierwave + Datamapper dirty bug</h1>
<p>Step 1: To demonstrate the bug, try uploading a new avatar image without modifying the person's name. The image will not be saved.</p>
<p>Step 2: Submit the form with a newly selected image and a modification to the person's name, and the image will be saved.</p>
<p>Step 3: To demonstrate the workaround, uncomment lines 43-46 and try Step 1 again. The image will be saved this time.</p>
<hr />
<form action="/update" method="POST" enctype="multipart/form-data">
<p>Name:<br />
<input type='text' name="person[name]" value="<%= Person.get(1).name %>" /></p>
<p>Avatar:<br />
<img src="<%= Person.get(1).avatar_url %>" /><br />
<input type='file' name="person[avatar]" /></p>
<p><input type='submit'/></p>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment