Reprocess Paperclip attachments in one line
script/runner -e development 'Article.all.each { |a| a.image.reprocess! if a.image.exists? }; "done"'
Related cards:
Deliver Paperclip attachments to authorized users only
When Paperclip attachments should only be downloadable for selected users, there are three ways to go.
The same applies to files in Carrierwave.
...
Reprocess only missing images with Paperclip
When a paperclip attachment gains a new style and you have many attachments, reprocessing can take ages. This is because all styles are being recomputed.
To create only missing images, patch Paperclip like this in your script that does the reproc...
Paperclip: undefined method `to_file' for #<Paperclip::Attachment:0000> (NoMethodError)
to_file
has been removed in Paperclip 3.0.1.
Instead of using File
to access Paperclip storage objects (like this: File.read(file.to_file.path)
) you can use
Paperclip.io_adapters.fo...
Always store your Paperclip attachments in a separate folder per environment
tl;dr: Always have your attachment path start with :rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/
.
The directory where you save your Paperclip attachments should not look like this:
storage/photos/1/...
stora...
Deleting stale Paperclip attachment styles from the server
Sometimes you add Paperclip image styles, sometimes you remove some. In order to only keep the files you actually need, you should remove stale Paperclip styles from your server.
This script has been used in production successful...
Copy a Paperclip attachment to another record
Just assign the existing attachment to another record:
new_photo = Photo.new
new_photo.image = old_photo.image
Paperclip will duplicate the file when saving.
To use this in forms, pimp your attachment container like this:
class Pho...
Check whether a Paperclip attachment exists
Don't simply test for the presence of the magic Paperclip attribute, it will return a paperclip Attachment
object and thus always be true:
- if user.photo.present? # always true
= image_tag(user.photo.url)
Use #exists?
instead:
...
How to run a small web server (one-liner)
Sometimes you just want to have a small web server that serves files to test something.
Serve the current directory
On Ruby 1.9.2+ you can do the following (".
" for current directory).
ruby -run -ehttpd . -p8000
Python 2.x offers a s...
One-liner syntax in RSpec's should-based and expect-based syntaxes
RSpec supports a one-liner syntax for setting an expectation on the subject
:
describe Array do
describe "when first created" do
it { should be_empty }
end
end
The example description "it should be empty" will be defined automat...
ActiveStorage: How to copy / clone an attachment from one record to another
Given there is a user with an attachable avatar:
class User < ApplicationRecord
has_one_attached :avatar
end
You can copy the avatar from one user to another user with the code below:
user_1 = User.first
user_2 = User.crea...