Carrier wave without s3 storage - ruby-on-rails-3

I am using carrier wave for image uploads and for testing purposes I don't want to use s3 storage.
This is the carrierwave.rb file
CarrierWave.configure do |config|
config.permissions = 0666
config.directory_permissions = 0777
config.fog_directory = 'xxx-development'
config.storage = :file
config.enable_processing = false
end
And in the ImageUploader class I have
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process resize_to_fill: [300, 300]
end
And when I push to heroku I get the following error:
rake aborted!
Fog provider can't be blank, Fog directory can't be blank
What is it I am doing wrong ?

If you want it conditional, perhaps set an environment condition on the fog_directory?
CarrierWave.configure do |config|
config.permissions = 0666
config.directory_permissions = 0777
config.fog_directory = 'xxx-development' unless Rails.env.development?
config.storage = :file
config.enable_processing = false
end

Related

Minimagick undefined method `width='

I want to use specific version of image by their width and height. So I followed How-to:-Get-image-dimensions this wiki, but got undefined method "width=".
My uploader looks like,
class S3uploaderUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
process :store_dimensions
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :detail do
process :quality => 90
process :store_dimensions
end
version :mainVertical do
process :quality => 80
process :store_dimensions
process :resize_to_fit => [240, 180]
end
version :mainHorizontal do
process :quality => 80
process :store_dimensions
process :resize_to_fit => [240, 320]
end
private
def store_dimensions
if file && model
model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]
end
end
end
What am I missing? Any suggestions? Thanks.
I got an idea from this post. conditional-image-resizing-with-carrierwave. It works well.
And I changed my code like this.
class S3uploaderUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :detail do
process :quality => 90
end
version :main, :if => :image? do
process :quality => 90
process :resize_to_fit => [240, 180] ,:if => :horizontal?
process :resize_to_fit => [240, 320] ,:if => :vertical?
end
def image?(new_file)
self.file.content_type.include? 'image'
end
def horizontal?(new_file)
image = MiniMagick::Image.open(self.file.file)
true if image[:height] < image[:width]
end
def vertical?(new_file)
image = MiniMagick::Image.open(self.file.file)
true if image[:height] > image[:width]
end
end

Rails Routing Error only in production

Hello i have this in routes.rb
namespace :admin do
root :to => "admin#index"
resources :employees
resources :customers
resources :users
end
frontend normally works, i can login to administration but there i have link like
<li><%= link_to "users", admin_users_path %></li>
etc..
if i click on that link i get this error
uninitialized constant Admin::UsersController
or if i click on admin_employees_path i get
uninitialized constant Admin::EmployeesController
and that behavior is at every link in administration
at server with rails s everything is fine :p
user controller is defined like that
class UsersController < Admin::AdminController
files location
controllers/admin/admin_controller.rb
controllers/users_controller.rb
My environments files
development.rb
Web::Application.configure do
config.cache_classes = false
config.whiny_nils = true
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = false
config.active_support.deprecation = :log
config.action_dispatch.best_standards_support = :builtin
config.active_record.mass_assignment_sanitizer = :strict
config.active_record.auto_explain_threshold_in_seconds = 0.5
config.assets.compress = false
config.assets.debug = true
end
production.rb
Web::Application.configure do
config.cache_classes = true # different
config.assets.compress = true # different
config.consider_all_requests_local = true # temporary true
config.action_controller.perform_caching = false
# not in development
config.serve_static_assets = false
config.assets.compile = true
config.assets.digest = true
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
end
You are defining your users resource under the admin namespace but not defining it in the controller.
Move your users_controller to /controllers/admin/users_controller and append the namespace to that class declaration
class Admin::UsersController < Admin::AdminController
Or move your
resources :user outside the admin namespace.

Error in Image crop using MiniMagick with carreirwave in Rails 3

I am trying to crop image using mini magick gem with carrierwave. I am facing following issue when i am creating user.
Errno::ENOENT in UsersController#create
No such file or directory - identify -ping /tmp/mini_magick20120919-5600-ai31ph.jpg
My Code :
model/user.rb
class User < ActiveRecord::Base
attr_accessor :crop_x, :crop_y, :crop_h, :crop_w
attr_accessible :username,:profile
after_update :reprocess_profile, :if => :cropping?
#field :username
mount_uploader :profile, ProfileUploader
def cropping?
!crop_x.blank? and !crop_y.blank? and !crop_h.blank? and !crop_w.blank?
end
def profile_geometry
#img = MiniMagick::Image.open(self.profile.large.path)
##geometry = {:width => img[:width], :height => img[:height] }
end
private
def reprocess_profile
#puts self.profile.large.path
#img = MiniMagick::Image.open(self.profile.large.path)
#crop_params = "#{crop_w}x#{crop_h}+#{crop_x}+#{crop_y}"
#img.crop(crop_params)
#img.write(self.profile.path)
#profile.recreate_versions!
end
end
uploader/profile_uploader.rb
# encoding: utf-8
class ProfileUploader < CarrierWave::Uploader::Base
# Include RMagick or ImageScience support:
#include CarrierWave::RMagick
# include CarrierWave::ImageScience
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# 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
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
version :large do
end
version :thumb do
process :resize_to_fill => [100, 100]
end
end
What would be the problem ? please suggest any solution.
Need to install imagemagick.
In ubuntu:
sudo apt-get install imagemagick

Carrierwave setup

please, could you please have a look to my config? I'm trying to setup carrierwave in my app but it doesn't work in the production server. It's working locally even as production environment. The thing is that it's saving the images into the tmp directory but the result is 'Empty file upload result'. I tried save to file and save to S3, same result. I'm using Passenger - Nginx.
I'm getting mad with this for two days now. Any idea or tip even about how I can debug this is welcome. I setup all permissions so I don't think it's a permissions issue. It could be a cache thing, the files are stored into tmp directory but it seems that the app don't see them as owned by the user???
Thanks!!!
#application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
Bundler.require(*Rails.groups(:assets => %w(development test)))
end
module MyApp
class Application < Rails::Application
config.encoding = "utf-8"
config.filter_parameters += [:password]
config.active_support.escape_html_entities_in_json = true
config.active_record.whitelist_attributes = true
config.assets.initialize_on_precompile = false
config.assets.enabled = true
config.assets.version = '1.0'
end
end
# avatar_uploader.rb
class AvatarUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
include ActiveModel::Conversion
extend ActiveModel::Naming
def extension_white_list
%w(jpg jpeg gif png mp3)
end
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :resize_to_fill => [200,200]
end
end
# carrierwave.rb
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS', # required
:aws_access_key_id => 'ACCESS', # required
:aws_secret_access_key => 'SECRET', # required
:region => 'eu-west-1' # optional, defaults to 'us-east-1'
}
config.fog_directory = 'my_app_bucket'
end
# production.rb
MyApp::Application.configure do
config.cache_classes = true
config.consider_all_requests_local = true # default false, debug true
config.action_controller.perform_caching = true #default true
config.serve_static_assets = true # Carrierwave true - Default false
config.assets.compress = true
config.assets.compile = false # false for real production
config.assets.digest = true
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
config.log_level = :debug
config.cache_store = :dalli_store
config.assets.precompile += %w( search.js )
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.action_mailer.default_url_options = { :host => 'localhost' }
end
Solved!
My ImageMagick install was missing delegates. Now:
convert -list configure
DELEGATES bzlib fontconfig freetype jpeg jng lqr pango png x11 xml zlib

Paperclip post process - How to compress image using jpegoptim/optpng

I would like to use jpegoptim or optipng to compress the image uploaded by users via Paperclip.
I have a Paperclip model configured as:
has_attached_file :image,
:styles => {:thumb => '50x50>', :preview => '270x270>' },
:url => "/system/:class/:attachment/:id/:basename_:style.:extension",
:path => ":rails_root/public/system/:class/:attachment/:id/:basename_:style.:extension"
Question 1:
Is it possible to compress the original image uploaded by user, then let Paperclip resize it , so there's only one compress process? and how to do it?
Question 2:
I am going to do it via the after_post_process callback, and I could get all the instances of three files from image.queued_for_write and I would like to trigger jpegoptim/optipng by the file extension, but when I use current_format = File.extname(file.path), I get something like: .jpg20120508-7991-cqcpf2. Is there away to get the extension string jpg? or is it safe that I just check if the extension string is contained in that string?
Since there's no other answers, here is how I do it in my project and it seems it's being working ok for several months.
class AttachedImage < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
validates_attachment_presence :image
validates_attachment_content_type :image, :content_type=>['image/jpeg', 'image/png', 'image/gif']
has_attached_file :image,
:styles => {:thumb => '50x50>', :preview => '270x270>' },
# :processors => [:image_compressor],
:url => "/system/:class/:attachment/:id/:basename_:style.:extension",
:path => ":rails_root/public/system/:class/:attachment/:id/:basename_:style.:extension"
after_post_process :compress
private
def compress
current_format = File.extname(image.queued_for_write[:original].path)
image.queued_for_write.each do |key, file|
reg_jpegoptim = /(jpg|jpeg|jfif)/i
reg_optipng = /(png|bmp|gif|pnm|tiff)/i
logger.info("Processing compression: key: #{key} - file: #{file.path} - ext: #{current_format}")
if current_format =~ reg_jpegoptim
compress_with_jpegoptim(file)
elsif current_format =~ reg_optipng
compress_with_optpng(file)
else
logger.info("File: #{file.path} is not compressed!")
end
end
end
def compress_with_jpegoptim(file)
current_size = File.size(file.path)
Paperclip.run("jpegoptim", "-o --strip-all #{file.path}")
compressed_size = File.size(file.path)
compressed_ratio = (current_size - compressed_size) / current_size.to_f
logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}")
logger.debug("JPEG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%")
end
def compress_with_optpng(file)
current_size = File.size(file.path)
Paperclip.run("optipng", "-o7 --strip=all #{file.path}")
compressed_size = File.size(file.path)
compressed_ratio = (current_size - compressed_size) / current_size.to_f
logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}")
logger.debug("PNG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%")
end
end
There are also some gems to optimize paperclip images:
paperclip-optimizer
paperclip-compressor
Might be a performance compromise but I got images better compressed with FFMPEG or AVCONV.
sudo apt-get install ffmpeg
= initializer
Paperclip.options[:command_path] = "/usr/bin/" # see `which ffmpeg`
= Modal
after_save :compress_with_ffmpeg
def compress_with_ffmpeg
[:thumb, :original, :medium].each do |type|
img_path = self.avtar.path(type)
Paperclip.run("ffmpeg", " -i #{img_path} #{img_path}")
end
end
I got 1.7MB image compressed to 302.9KB!!!