Rails3 and Paperclip - ruby-on-rails

I have migrated my application from rails 2.3 to rails3 and i have a problem with paperclip.
I saw there was a branch for rails3 on paperclip git.
So I added "gem 'paperclip', :git => 'git://github.com/thoughtbot/paperclip.git', :branch => 'rails3'" into the Gemfile and launch the command bundle install.
Once paperclip installed, the upload worked fine but not the styles. I saw a hack to fix it.
# in lib/paperclip/attachment.rb at line 293
def callback which #:nodoc:
# replace this line...
# instance.run_callbacks(which, #queued_for_write){|result,obj| result == false }
# with this:
instance.run_callbacks(which, #queued_for_write)
end
The styles are ok after that, but i'm not able to active the processor. My code is :
has_attached_file :image,
:default_url => "/images/nopicture.jpg",
:styles => { :large => "800x600>",
:cropped => Proc.new { |instance| "#{instance.width}x#{instance.height}>" },
:crop => "300x300>" },
:processors => [:cropper]
My processor is located in RAILS_APP/lib/paperclip_processors/cropper.rb and contains :
module Paperclip
class Cropper < Thumbnail
def transformation_command
if crop_command and !skip_crop?
crop_command + super.sub(/ -crop \S+/, '')
else
super
end
end
def crop_command
target = #attachment.instance
trans = "";
trans << " -crop #{target.crop_w}x#{target.crop_h}+#{target.crop_x}+#{target.crop_y}" if target.cropping?
trans << " -resize \"#{target.width}x#{target.height}\""
trans
end
def skip_crop?
["800x600>", "300x300>"].include?(#target_geometry.to_s)
end
end
end
My problem is that i got this error message : uninitialized constant Paperclip::Cropper
The cropped processor is not loaded.
Is anybody has an idea to fix that ?
For information my application works fine on rails 2.3.4.

I have the same problem. Seems like paperclip processors are not loaded in rails 3. Until someone fix it, I hacked the problem moving the cropper.rb file inside /config/initializers

Restart server, worked for me :)

I got "uninitialized constant Paperclip::Cropper"exception too.
But you can move your cropper.rb to the paperclip lib directory and add require 'paperclip/cropper.rb'. It work for me, but I use bundler, so it seems very ugly...

In your Photo.rb class, or whichever one you used to have require '.../cropper.rb' you have to put the root of your project in the path as well:
require "#{config.root}/lib/paperclip_processors/cropper.rb" # required to make cropping work.
before it used to just be require "lib/..."

Yep, install Paperclip as a plugin and it will work

I recommend you carrierwave instead paperclip, is much fast and easier https://github.com/jnicklas/carrierwave

I have the same problem. I'm using the paperclip gem from this repository:
gem "paperclip", :git => "git://github.com/JasonKing/paperclip.git", :branch => "rails3"
And I also get "uninitialized constant Paperclip::Cropper". Restarting the server didn't work!

Related

fixture_file_upload gives a "{***} has an extension that does not match its contents" from paperclip model rails 4.2.1

I'm having this issue with uploading paperclip documents with rails fixture_file_upload (after upgrading rails version)
Knowing that paperclip 4.0 and above requires validating content_type, My specs still fails with the error: File has an extension that does not match its contents even after either after the validation or specifically requesting do_not_validate_attachment_file_type.
I'm having this scenario in multiple(all my) paperclip models...
An example is as follow:
Model:
class SignatureFile < ActiveRecord::Base
...
has_attached_file :file
VALID_CONTENT_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/gif"]
validates_attachment :file, content_type: { content_type: VALID_CONTENT_TYPES },
convert_options: { all: '-auto-orient' },
processors: [:compression]
...
end
Spec:
image = fixture_file_upload('spec/fixtures/mobile_api/sample.jpg', 'image/jpg')
When I try to save image above, it fails, and image.errors.full_messages gives:
"File has an extension that does not match its contents"
Suffice to say I have a bunch of scenarios like this one which was previously passing before the upgrade.
Below are versions of the related gems I have:
gem 'rails', '4.2.7.1'
gem 'paperclip', '4.2.1'
gem 'paperclip-compression', '0.3.7'
gem 'rspec-rails', '3.4.2'
What can I be missing here?
You might be missing file, sadly the error isn't more precise in those cases. Read in the paperclip docs.

PaperClip Error NotIdentifiedByImageMagickError when scaling images

I have been banging my head against this for several days. Recently, my image uploader has stopped working properly. I have investigated several possibilities, but have none of the suggested solutions have worked in my case.
The error message is:
#<Paperclip::Errors::NotIdentifiedByImageMagickError:Paperclip::Errors::NotIdentifiedByImageMagickError>
Here are the details:
Mac OS X 10.8.3
ImageMagick 6.8.4-4 2013-03-29
libtool => /usr/bin/libtool
Rails 3.2.13
Ruby 1.9.3p194
development.rb contains appropriate path (and I have verified that it is correct using which identify)
Paperclip.options[:command_path] = "/usr/local/bin/"
Gemfile.lock (relevant portion)
paperclip (3.4.1)
activemodel (>= 3.0.0)
activerecord (>= 3.0.0)
activesupport (>= 3.0.0)
cocaine (~> 0.5.0)
MODEL (I am updating a classroom object, but the picture resides in the location model. (Classroom has_one :location, :as => :locatable)
Model location.rb
class Location < ActiveRecord::Base
## Paperclip method for uploading location images
has_attached_file :picture, :styles => {:show => "1200x500#", :medium => "300x300#", :thumb => "100x100>"}, :convert_options => {:show => "-gravity center"}
has_attached_file :building_sign, :styles => { :show => ["1200x500#", :jpg], :medium => ["300x300#", :jpg], :thumb => ["100x100#", :jpg] }, :convert_options => {:show => "-gravity center"}
belongs_to :locatable, :polymorphic => true
belongs_to :location_type
validates :name, :presence => true
validates :latitude, :presence => true,
:length => {:within => 9..18},
:numericality => true
validates :longitude, :presence => true,
:length => {:within => 9..18},
:numericality => true
end
Controller classrooms_controller.rb
def update
#classroom = Classroom.find_by_facility_code_heprod(params[:id].upcase)
respond_to do |format|
if #classroom.update_attributes(params[:classroom])
format.html { redirect_to(#classroom, :notice => 'Classroom was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #classroom.errors, :status => :unprocessable_entity }
end
end
end
What I've tried.
I've made sure that the image name is simple (USB2230.jpg), no colons.
I've updated the version of ImageMagick to the most recent.
I've also re-downloaded and reinstalled the CommandLine Tools for 10.8.3 (someone suggested that the issue might be related to an outdated libtool).
I've rebooted the computer.
I've tried variations on gem versions including
# variation 1
gem 'paperclip', '~> 2.8.0'
gem "cocaine", "=0.3.2"
# variation 2
gem "paperclip", "~> 3.4.0"
gem "cocaine", "= 0.4"
# variation 3 (which is what is reflected in the included Gemfile.lock info above).
gem "paperclip", "~> 3.4.0"
If I remove the scaling,
:styles => {:show => "1200x500#", :medium => "300x300#", :thumb => "100x100>"},
:convert_options => {:show => "-gravity center"}
the upload works, but I kind of need the scaling ;-)
Can anyone see something I am missing?
We just ran into this issue, and it turned out to be an issue where ghostscript wasn't installed. I took the advise of Scott Cornwell and removed the silencing of errors, and then determined that convert was failing because ghostscript wasn't available.
brew install ghostscript
Fixed the issue for us.
I had the same issue, although my server is on Linux. Can't tell you exactly how to do it because I don't have a Mac to test, but hopefully this points you in the right direction.
This worked for me with ImageMagick 6.8.5-5, Paperclip 3.4.2, latest version of cocaine, Rails 3.2.13:
I went into geometry_detector_factory.rb in the Paperclip gem and commented out the 2 lines around the identify call: (this step is not necessary, just explaining what I did to determine the problem)
#silence_stream(STDERR) do
Paperclip.run("identify", "-format '%wx%h,%[exif:orientation]' :file", :file => "#{path}[0]")
#end
along with the corresponding "end" statement. This allowed me to see the errors on the command line when running the "identify" command.
Basically the error said: "no decode delegate for this image format"
You can probably look up that error and get it figured out, but basically what I did was go to usr/local/bin and run: (also not necessary, unless you want to see what you have installed)
convert -list configure
and look for the DELEGATES line. I had another Linux server where ImageMagick was working and after comparing the two I realized the new one had only 2 delegates installed. I was able to run:
yum install ImageMagick-devel
and then recompile ImageMagick with make, make install and it worked.
You can also find the delegates manually on the ImageMagick site and install them one by one but that library pretty much covered it for me.
Debugging ImageMagick? Ain't nobody got time for that!
Had the problem on my window dev environment, using paperclip 3.5.2, cocaine 0.5.3, and ImageMagic 6.8.8.
Solution was to add:
Paperclip.options[:command_path] = 'C:\Program Files\ImageMagick-6.8.8-Q16'
to config/environment/development.rb
I had similar issue, but older PaperClip (3.0.2).
In my case I fixed it with:
gem 'cocaine', '0.3.2'
I just solved this issue.
brew makes a directory call Cellar, /usr/local/Cellar
Verify if you don`t have two ImageMagick, i had one named ImageMagick-Ruby182, so, if you have it run brew uninstall ImageMagick-Ruby182, and also the normal imagemagick, and reinstall image magic.
Reinstalling libtool brew install libtool worked for me.
Please update the version of paperclip gem and cocaine gem.
Set PaperClip version: 3.4.1
Set Cocaine version: 0.5.
I faced the same problem and my issue was already there in paperclip gem github issues
You already mentioned that you tried upgrading ImageMagick, but I had the same issue and upgrading to ImageMagick 6.8.0-10 2013-03-03 fixed it for me.
Had same issue with image_magic that was breaking our paperclip functionality in production, but not in development (weird, I know).
Yet even after removing imagemagick from our gemfile and Gemfile.lock locally (running bundle install and all that stuff) and then deploying back to production on heroku, the error persisted in production! (weird, I know).
What ended up doing the trick was running:
$ heroku repo:purge_cache -a myAppName
(Taken from: https://github.com/heroku/heroku-repo#purge_cache)
When you deploy your app, Heroku caches some things like your assets and installed gems in order to speed up deployment.
Although this is a great feature, it can have side-effects sometimes, and in this case, it seems that something about the imagemagick gem got "stuck" in production's cache, which is why purging solved the issue for us (since after purging, your app will rebuild itself from scratch on your next deployment)
I have the same issue, and I solved it, when i configure the dynamic linker run-time bindings to create the necessary links and cache to the most recent shared libraries using the ldconfig command.
So you need to use the following command:
sudo ldconfig /usr/local/lib
Actually, I advice to re-install imagemagick using steps at how-to-install-image-magick-and-setup-paperclip.
Just for the record:
brew uninstall libtool
brew install libtool
brew uninstall jpeg
brew install jpeg
brew link --overwrite jpeg
brew unlink freetype && brew link freetype

Image file is not recognized by the 'identify' command. (heroku)

I'm trying to have Paperclip working with Heroku and Amazon S3.
Everything works fine on localhost (mac OS and Amazon), but when I'm deploying to heroku and trying the feature, I have this error :
2 errors prohibited this area from being saved:
Asset /tmp/paris20121005-2-2cwxgx.jpg is not recognized by the 'identify' command.
Asset /tmp/paris20121005-2-2cwxgx.jpg is not recognized by the 'identify' command.
It works when I remove the :styles => { } option in my model, but the file isn't processed (I need different image sizes).
I also have the rmagick gem in my gemfile.
Here is my gemfile (only the paperclip part) :
gem "paperclip"
gem "rmagick", :require => 'RMagick'
gem 'aws-sdk', '~> 1.3.4'
I don't have Paperclip.options[:command_path] set in my environment.rb or production.rb so no problem on this side.
Here is my model :
class Area < ActiveRecord::Base
require 'RMagick'
has_attached_file :asset, :styles => { :medium => "300x300>", :thumb => "180x190>" },
:storage => :s3,
:s3_credentials => "#{::Rails.root.to_s}/config/s3.yml",
:url => :s3_domain_url.to_s,
:path => "/:style/:id/:filename"
end
Any clue on that ? I've crawled every topics about it and nothing seems to work...
Thanks
Apparently the new update to Cocaine gem (0.4.0) breaks the file names for Paperclip and ImageMagick. try rolling back to the previous version (0.3.2), it worked for me.
See here:
https://github.com/thoughtbot/paperclip/issues/1038
PS I believe RMagick is no longer needed on Heroku, works fine for me without it

Rails 3 app + paperclip gem + production mode = download of empty files

I've installed the paperclip gem for a Rails 3 application. Everything works fine in development mode. However, when running in production mode, if I upload a file and then try to download it again, it downloads a file with the correct name and extension, but it is an empty file. When looking on the server, the file does get uploaded and is in the correct directory. (I have an "uploads" folder in my application root.)
Anyone had this happen?
My model:
# app/models/document.rb
class Document < ActiveRecord::Base
belongs_to :kase
has_attached_file :document, :path => (Rails.root + "uploads/:class/:kase_id/:id").to_s, :url => ":class/:id"
validates_attachment_presence :document
validates_attachment_content_type :document, :content_type => [
'application/pdf',
'image/png',
'image/jpeg',
'image/pjpeg',
'text/plain'
]
end
My controller:
# app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
respond_to :html
before_filter :initialize_kase # Sets the #kase instance
def show
#document = #kase.documents.find(params[:id])
send_file #document.document.path, :filename => #document.document_file_name, :content_type => #document.document_content_type
end
end
And my initializer (setting the :kase_id placeholder used in has_attached_file above:
# config/initializers/paperclip.rb
Paperclip.interpolates('kase_id') do |attachment, style|
"kases/#{attachment.instance.kase.id.to_s}"
end
I should probably mention, too, that I am accessing this as a nested controller (/kases/XX/documents/XX). Not sure if that has an effect or not...
If you are using Apache and Passenger, (possibly other servers as well) and have the line:
config.action_dispatch.x_sendfile_header = "X-Sendfile"
in your production.rb env file, then you have two options:
Install the apache module mod-xsendfile
Comment out that line and let Rails send the files instead of Apache, like it does in development mode.
Are you carrying over the uploads directory each time you deploy your app to production? Assuming that you're using capistrano (or similar) for deployment, each time you deploy you might be creating a new uploads directory in the newly-deployed release directory. In that case, the previously-uploaded files are residing in older deployed releases (if you didn't delete those) and would no longer be accessible to your app.
You want to create e.g. shared/uploads directory that is symlinked into your app on each deploy.

Carrierwave/Fog - Argument error, provider not recognized

I'm using Carrierwave 0.5.3 and Fog to upload images to Amazon-S3.
The setup works smoothly when running locally, no errors.
But when running on Heroku, uploads fail with this message:
2011-03-31T12:53:46-07:00 app[web.1]: ArgumentError ( is not a recognized storage provider):
2011-03-31T12:53:46-07:00 app[web.1]: app/controllers/useditems_controller.rb:36:in `create'
I've got an initializer:
# /config/initializers/fog.rb
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS',
:aws_access_key_id => 'secret',
:aws_secret_access_key => 'also secret',
:region => 'eu-west-1'
}
config.fog_directory = 'jabberwocky'
end
And an uploader:
# /app/uploaders/image_uploader.rb
# encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or ImageScience support:
include CarrierWave::RMagick
# Choose what kind of storage to use for this uploader:
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"useditems"
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
# Create different versions of your uploaded files:
version :thumb do
process :resize_to_limit => [220, 2000]
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
end
I've traced the error message to Fog, and it seems that Fog, under Heroku, isn't getting the config info from the initializer. :provider is somehow empty. But I'm stumped as to how to fix it.
Any help would be much appreciated.
I'm using:
rails 3.0.4
heroku 1.19.1
fog 0.7.1
ruby 1.9.2 under rvm
The error was due to the fact that I had mistakenly added the initializer to the .gitignore-file. Thus, it was never uploaded to Heroku.
Adding this for completeness...
After smashing my head against the wall for hours with this error message, I found out that I had this line at the beginning of the carrierwave initializer:
if Rails.env.test?
...
So the initializer was only considered in the test environment. After removing it, everything worked as expected.

Resources