How to store file with unicode characters using paperclip - ruby-on-rails-3

I'm using paperclip gem to process some images and store them to Amazon S3. Each image represents person's name. I want to add support for names with unicode characters as well, but I can't make it work because of paperclip fails to upload a file with unicode characters in its name.
I can't just change Ñ to N before uploading, because then I'll overwrite an image that was uploaded with letter N.
Eg.
Two users: NUÑO and NUNO. I can't just tell paperclip to upload NUÑO.jpg as NUNO.jpg because that will overwrite previous NUNO.jpg.
Here's my pretty much standard production/staging environment configuration:
config.paperclip_defaults = {
:storage => :s3,
:url => ':s3_domain_url',
:path => 'assets/:class/:id/:style.:extension',
:s3_credentials => {
:bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY_ID']
}
}
And here's related class with image attachment:
class NameSpread < ActiveRecord::Base
(...)
has_attached_file :rendered_image,
default_url: lambda { |attach| attach.instance.processing_image },
path: lambda { |attach| attach.instance.save_path },
styles: { (..) },
processors: [ :name_spread_processor ],
default_style: :spread
(...)
end
Here's save_path method:
def save_path
if Rails.env.production? || Rails.env.staging?
"assets/:class/#{gender}/#{name}/:style.jpg"
else
"#{Rails.root}/public/assets/:class/#{gender}/#{name}/:style.jpg"
end
end
This is the part that gets messed up: #{name}
Any ideas?

After two days of debugging, I found the solution.
I updated from ruby 1.9.2 to 2.0.0 and now everything works...

Related

How can we restrict file uploads with valid file type but invalid content-type - Rails

In my Rails web application, I have to upload audio and video files and for validating against invalid file types, I have used jquery-validation engine and I could do the same successfully. But, if I create a text file and change the extension from .txt to .mp3, e.g. test.txt to test.mp3, it will be taken as valid by jquery validation engine as the file extension is valid for an audio.
I want to check the content type also. When I opened the test.mp3 in a player, it showed me an error message Stream contains no data. I want this kind of validation to be performed in the interface. Is it possible in Rails?
I'm using,
Rails 3.2.13
Ruby 2.0.0-dev
Hope anyone can help me out. Thanks :)-
I recommend you to check paperclip gem its a file attachment library for Active Record. This library is very straightforward to use and make validations with each content type. For example if you want to validate an Image you can by the next validation:
class User < ActiveRecord::Base
attr_accessible :avatar
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment :avatar,
:presence => true, :content_type => { :content_type => "image/jpg" },
:size => { :in => 0..500.kilobytes }
end
Hope it helps.

Paperclip::Errors::NotIdentifiedByImageMagickError + Heroku

I currently have an application using paperclip that allows users to upload their creatives. This has worked flawless thus far when it comes to a user uploading an image file. We have since tested to upload a .mov file and I get this error:
Creative Paperclip::Errors::NotIdentifiedByImageMagickError
The weird thing, this error is only generated on Heroku. I can upload .mov files just fine on my local host.
My Current Gem Setup:
paperclip (3.4.1, 3.4.0)
paperclip-aws (1.6.7, 1.6.6)
paperclip-ffmpeg (0.10.2)
cocaine (0.5.1, 0.4.2)
Event.rb
has_attached_file :creative,
:processors => [:ffmpeg],
:styles => {
:thumb => [:geometry => "250x150", :format => 'png'],
:custcreative => [:geometry => "275x75", :format => 'png'],
:creativepreview => ["275x195",:png]
},
:url => "***",
:path => "***",
:s3_domain_url => "***",
:storage => :s3,
:s3_credentials => Rails.root.join("config/s3.yml"),
:bucket => '***',
:s3_permissions => :public_read,
:s3_protocol => "http",
:convert_options => { :all => "-auto-orient" },
:encode => 'utf8'
Spending hours trying to figure out why this works locally but throwing error on Heroku.
I even tried removing the :style setting, but still did not work.
TIA
EDIT
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/MidPen20130413-2-1mzetus.mov[0]'
Well, here is the answer in case any other newbies like us come across the same problem. The issue is with the geometry method that is being used for image cropping. The way it is suggested in railscasts assumes the file is in a local system and that needs to be changed.
OLD METHOD:
def avatar_geometry(style = :original)
#geometry ||= {}
#geometry[style] ||= Paperclip::Geometry.from_file(avatar.path(style))
end
NEW METHOD
def avatar_geometry(style = :original)
#geometry ||= {}
avatar_path = (avatar.options[:storage] == :s3) ? avatar.url(style) : avatar.path(style)
#geometry[style] ||= Paperclip::Geometry.from_file(avatar_path)
end

Default_url in Paperclip Broke with Asset Pipeline Upgrade

I'm using Paperclip and have a default_url option like this for one of my attachments:
:default_url => '/images/missing_:style.png'
The asset pipeline obviously doesn't like this since the directories moved. What's the best way to handle this? I have two styles for this picture (:mini and :thumb).
:default_url => ActionController::Base.helpers.asset_path('missing_:style.png')
Then put the default images in app/assets/images/
Tested only on Rails 4.
To make it work in production, we have to pass the name of an existing file to the asset_path helper. Passing a string containing a placeholder like "missing_:style.png" therefore doesn't work. I used a custom interpolation as a workaround:
# config/initializers/paperclip.rb
Paperclip.interpolates(:placeholder) do |attachment, style|
ActionController::Base.helpers.asset_path("missing_#{style}.png")
end
Note that you must not prefix the path with images/ even if your image is located in app/assets/images. Then use it like:
# app/models/some_model.rb
has_attached_file(:thumbnail,
:default_url => ':placeholder',
:styles => { ... })
Now default urls with correct digest hashes are played out in production.
The default_url option also takes a lambda, but I could not find a way to determine the requested style since interpolations are only applied to the result of the lambda.
Just make sure that in your views all your paperclip images are rendered with image_tag.
<%= image_tag my_model.attachment.url(:icon) %>
That way, all of paperclip's :crazy :symbol :interpolation will have happened to the url string before Rails tries to resolve it to an asset in the pipeline.
Also, make sure your :default_url is asset compatible...if missing_icon.png is at app/assets/images/missing_icon.png, then :default_url should be simply "missing_:style.png"
<%= image_tag my_model.attachment.url(:icon) %>
# resolves to...
<%= image_tag "missing_icon.png" %>
# which in development resolves to...
<img src="/assets/missing_icon.png">
I got the error(even for a single style) at assets:precompile with
:default_url => ActionController::Base.helpers.asset_path('missing.png')
So I hooked with a method like this
# supposing this is for avatar in User model
has_attached_file :avatar,
:styles => {..},
:default_url => lambda { |avatar| avatar.instance.set_default_url}
def set_default_url
ActionController::Base.helpers.asset_path('missing.png')
end
I didn't try for multiple styles, but this works for my situation.
this works for me:
has_attached_file :avatar, :styles => { :small => "52x52",
:medium => "200x200>", :large=> "300x300", :thumb => "100x100>" },
:default_url => "missing_:style.png"
just place images in your assets/images folder named: missing_large.png, missing_medium.png, missing_small.png and missing_thumb.png
In rails 4.0.0 and paperclip 4.1.1 this worked for me:
has_attached_file :avatar,
styles: { medium: '300x300#', small: '100x100#', thumb: '25x25#' },
default_url: ->(attachment) { 'avatar/:style.gif' },
convert_options: { all: '-set colorspace sRGB -strip' }
I ended up having to use something like the following.
DEFAULT_URL = "#{Rails.configuration.action_controller.asset_host}#{Rails.configuration.assets.prefix}/:attachment/:style/missing.png"
has_attached_file :art, :styles => { :large => "398x398#", :medium => "200x200#", :small=>"100x100#", :smaller=>"50x50#", :smallest=>"25x25"}, :path=>"images/:attachment/:id/:style/:basename.:extension", :default_url => DEFAULT_URL
I statically compile the assets and was getting an error in production, this helped me.
In your model file, change this line:
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
by removing this:
/images/
Create a folder for each style, in this example medium and thumb, in assests/images and place an image called missing.png there (or whatever name you want it to have of course, as long as it matches the file name in the model)
Worked for me.
I've solved this problem by using a custom interpolator.
The problem from other solutions that suggest using
:default_url => ActionController::Base.helpers.asset_path('missing_:style.png')
is that you will get an error saying "missing_style.png" is not precompiled.
I created an initializer with the following code:
module Paperclip
module AssetPipeline
module Interpolator
def self.interpolate(pattern, *args)
ActionController::Base.helpers.asset_path Paperclip::Interpolations.interpolate(pattern, *args)
end
end
end
end
Then in my model I would do:
has_attached_file :image, interpolator: Paperclip::AssetPipeline::Interpolator, ...
Just remove the / from /images/pic.png: images/pic.png

Rails 3: How can I make Paperclip-FFMPEG work?

I have Rails 3.0.3 with these gems:
delayed_job 2.1.4
delayed_paperclip 0.7.1
paperclip 2.3.16
paperclip-ffmpeg 0.7.0
(This combination is very specific. Some newer gems will not work with others.)
Here's my Video model:
class Video < Upload
has_attached_file :file, :default_style => :view, :processors => [:ffmpeg],
:url => '/system/:class/:attachment/:id/:style/:basename.:extension',
:path => ':rails_root/public/system/:class/:attachment/:id/:style' \
+ '/:basename.:extension',
:default_url => '/images/en/processing.png',
:styles => {
:mp4video => { :geometry => '520x390', :format => 'mp4',
:convert_options => { :output => { :vcodec => 'libx264',
:vpre => 'ipod640', :b => '250k', :bt => '50k',
:acodec => 'libfaac', :ab => '56k', :ac => 2 } } },
:oggvideo => { :geometry => '520x390', :format => 'ogg',
:convert_options => { :output => { :vcodec => 'libtheora',
:b => '250k', :bt => '50k', :acodec => 'libvorbis',
:ab => '56k', :ac => 2 } } },
:view => { :geometry => '520x390', :format => 'jpg', :time => 1 },
:preview => { :geometry => '160x120', :format => 'jpg', :time => 1 }
}
validates_attachment_content_type :file, :content_type => VIDEOTYPES,
:if => Proc.new { |upload| upload.file.file? }
process_in_background :file
end
When creating a new Video object with attachment, the original is saved, but no conversion will be done. Even calling Video.last.file.reprocess! won't to a thing except returning true. (Not sure what "true" means in this case as it didn't work.)
I tried hardcoding the path to ffmpeg in Paperclip::options[:command_path]. I even tried deleting the paperclip-ffmpeg.rb file and replacing it with a blank file. Really thinking I'd get an exception by doing the later, instead, I simply got "true" again.
It feels like the paperclip-ffmpeg.rb is being loaded, because it is required by config/application.rb, but nothing is called in it when trying to generate a thumbnail or convert a video.
Can anyone help me with this? Thanks in advance!
Looks like I solved this problem myself, and it was caused by something I did.
I wrote my own script to import files and the database from an older app to Rails. The files were in place, but someone I updated the database with the wrong file extensions (in this case, ".jpg" instead of ".MOV").
Paperclip will verify first to see if the original file exists before calling any processor, based on the file name stored in the database. As it didn't, Paperclip just didn't do anything. Once I had the data corrected, everything ran as expected. (I had problems with FFMPEG, but that's a different issue.)
My apologies if I wasted anyone's time. Hope this can be helpful for someone.
I use a similar configuration for one of my project (but Rails 3.1.1) and everything works fine. I added paperclip-ffmpeg to my Gemfile not with config/application.rb. Maybe this helps!?

Rails paperclip change file

I used rmagick in Rails to convert images I upload from one file type to JPEG. I can make it call from the new image now; I did:
image = Magick::ImageList.new 'public/system/photos/' + #picture.id.to_s +
'/original/' + #picture.photo_file_name
image.write 'public/system/photos/' + #picture.id.to_s + '/original/' +
#picture.photo_file_name.sub(/\.\w*/, '.jpg')
#picture.photo_file_name = #picture.photo_file_name.sub /\.\w*/,'.jpg'
Now I have created two files, how should delete the original file, or overwrite the original file rather than create a new one like I am now?
Re: the discussion in the comments, here's an example from the Paperclip docs:
class User < ActiveRecord::Base
has_attached_file :photo,
:styles => {
:small => {
:geometry => '38x38#',
:quality => 40,
:format => 'JPG'
},
:medium => {
:geometry => '92x92#',
:quality => 50
}
end
Note the ":format => 'JPG'" line. As you can see it's trivial to tell Paperclip to convert the file to JPEG while it's going about the rest of the business, so if you're using Paperclip already you don't need to do a separate conversion step with rmagick directly.