public
Last active

Carrierwave, DataMapper, & Sinatra starring in "Imagine the Possibilities"

  • Download Gist
helpers.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
def is_ajax_request?
if respond_to? :content_type
if request.xhr?
true
else
false
end
else
false
end
end
 
def json_data(data)
content_type "application/json" if is_ajax_request?
{:data => data}.to_json
end
 
def json_errors(*objs)
content_type "application/json" if is_ajax_request?
errors = {}
objs.each do |o|
if o.respond_to? :errors
errors[o.class.name.snake_case] = o.errors.to_hash
else
unless errors['general']
errors['general'] = []
end
errors['general'].push(*o)
end
end
{:errors => errors}.to_json
end
 
def json_redirect(url)
content_type "application/json" if is_ajax_request?
{:redirect => url}.to_json
end
init.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
require 'sinatra'
require 'helpers'
require 'models'
 
post '/settings_image' do
require_login
@user = session_user
@user.image = params['user']['image']
if @user.save
@user.reload
json_data({
:image => @user.image.url,
:image_icon40 => @user.image.icon40.url,
:image_icon60 => @user.image.icon60.url
})
else
json_errors("Failed",@user)
end
end
models.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
class UserImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
if settings.environment == :production
storage :s3
else
storage :file
end
def store_dir
"uploads/users/#{model.id}/image"
end
def extensions_white_list
%w(jpg jpeg gif png)
end
process :resize_to_limit => [720,720]
version :icon40 do
process :resize_to_fill => [40,40]
end
version :icon60 do
process :resize_to_fill => [60,60]
end
version :profile do
process :resize_to_limit => [180,180]
end
end
 
class User
include DataMapper::Resource
 
property :id, Serial
timestamps :at, :on
property :username, String
 
property :image, String, :auto_validation => false
mount_uploader :image, UserImageUploader
end

Hey thanks for all this. Is it possible we can see the source for the form used to upload the image?

I would like to see the upload form also. What do you send to the mount_uploader :image property?? Sinatra uses params[:name] and either [:filename] or [:tmpfile]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.