EDIT – ‘carrierwave’ doesn’t work with Sinatra 1.3.
Sinatra 1.2.7 rocks this code!
I’m learning Ruby, and just finished this awesome Sinatra tutorial:
http://net.tutsplus.com/tutorials/ruby/singing-with-sinatra-the-encore/
The complete, working code is here (no Bundler, so requires a couple gems to be installed)
http://nettuts.s3.amazonaws.com/953_sinatra3/Source.zip
I feel good, I want to learn more! The next challenge I’ve set for myself is to add file uploading capability to that tutorial, and I’m stumped. I want to use Carrierwave, and am attempting to integrate it into the completed tutorial.
First, I’m requiring ‘carrierwave’ and ‘carrierwave-datamapper’:
require 'carrierwave'
require 'carrierwave/datamapper'
Then I’m creating a new class:
class MyUploader < CarrierWave::Uploader::Base #via a Carrierwave tutorial
storage :file
end
Adding to the Notes class:
class Note
include DataMapper::Resource
property :id, Serial
property :content, Text, :required => true
property :complete, Boolean, :required => true, :default => 0
property :created_at, DateTime
property :updated_at, DateTime
property :image, String, :auto_validation => false # trying to add image uploading
mount_uploader :image, MyUploader # trying to add image uploading
end
Adding to post:
post '/' do
n = Note.new
n.content = params[:content]
n.image = params[:image] # trying to add image uploading
n.created_at = Time.now
n.updated_at = Time.now
n.upload =
if n.save
redirect '/', :notice => 'Note created successfully.'
else
redirect '/', :error => 'Failed to save note.'
end
end
Lastly, I’m adding uploading to the form:
<section id="add">
<form action="/" method="post" enctype="multipart/form-data">
<textarea name="content" placeholder="Your note…"></textarea>
<p><input type="file" name="image" /></p>
<input type="submit" value="Take Note!">
</form>
</section>
I’m getting this error:
/gems/carrierwave-0.5.7/lib/carrierwave.rb:107:in `<top (required)>': private method `public' called for Sinatra::Application:Class (NoMethodError)
But of course if I don’t require ‘carrierwave’, I get an error when MyUploader tries to inherit from it…
Thanks in advance for any tips. I feel so close here, and yet so far!
This error looks like it’s caused by a recent change to sinatra. This is in the changelog for version 1.3:
Either check if there’s a more recent version of carrierwave or use a previous version of sinatra.