Hello I've been looking around at all the various tutorials out there for Paperclip post processing but somehow I can not get the 'Make' method to invoke.
Take a look at line 36 here... http://pastie.org/private/epfgcxywhyh4wpmozypg
It uploads normally without any errors or warnings but I can never see the puts statement in the make method which tells me that this isn't being invoked.
EDIT
I can run this in the model without a problem and I get True,
def class_exists?(class_name)
klass = Paperclip.const_get(class_name)
return klass.is_a?(Class)
rescue NameError
return false
end
Any ideas?
Two days ago I was facing the same problem. Here what I did to make it work:
Go to the command prompt and type: "which convert" command. This is ImageMagick command so if it says /usr/bin/convert then try adding
Paperclip.options[:command_path] = "/usr/bin"
in your config/environments/development.rb. Remove /convert from what you get over there.
then change name of your file file_contents.rb to paperclip_postprocess.rb and put it into directory: RAILS_ROOT/config/initializers/paperclip_postprocess.rb
You can cross check if your attachment is being processed or not by adding following lines in your model:
before_post_process :before_post_process
after_post_process :after_post_process
def before_post_process
puts "===========Before processing attachment==========="
end
def after_post_process
puts "-----------After processign attachment------------"
end
Take a look here
It worked for me at least.
I noticed this line in the Paperclip README:
NOTE: Because processors operate by turning the original attachment into the styles, no processors will be run if there are no styles defined.
And looking at your paste, you define everything but a :style argument, so maybe that's the problem?
Related
I was going through one of the PR in rails 6 where they have added a color property to the unpermitted parameter. I found it quite imperative for my application because we usually have a very long log. I thought to include the same functionality in my Rails 5 application
I created an ext folder inside my app and there added the below code
And in initializers folder
require "#{Rails.root}/app/ext/action_controller_override.rb"
file_name: action_controller_override.rb
ActionController::LogSubscriber.class_eval do
def unpermitted_parameters(event)
debug do
unpermitted_keys = event.payload[:keys]
color("Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.map { |e| ":#{e}" }.join(", ")}", RED)
end
end
end
But the above code giving me error.
Could not log unpermitted_parameters.action_controller event. NameError: uninitialized constant RED
So, can anyone shed a light on it and tell me where I am going wrong
I suggest to keep your code under config/initializers folder as .rb file which will open class and override as per your code.
Also, Have a look on 3 ways to monkey patch
Finally, I found the solution
"Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.map { |e| ":#{e}" }.join(", ")}".green
The keyword green is given by colorize gem
I'm writing tests with rspec and am a bit struggling with Paperclip 4. At the moment I'm using webmock to stub requests but image processing is slowing tests down.
Everything I read suggest to use stubs like so:
Profile.any_instance.stub(:save_attached_files).and_return(true)
It doesn't work since :save_attached_files disappeared with Paperclip 4 as far as I can tell.
What's the proper way to do it now ?
Thanks
Add this to your rails_helper.rb in your config block:
RSpec.configure do |config|
# Stub saving of files to S3
config.before(:each) do
allow_any_instance_of(Paperclip::Attachment).to receive(:save).and_return(true)
end
end
It doesn't exactly answer my question, but I found a way to run faster specs thanks to this dev blog, so I'm posting it if it can help someone else.
Just add this piece of code at the beginning of your spec file or in a helper. My tests are running 3x faster now.
# We stub some Paperclip methods - so it won't call shell slow commands
# This allows us to speedup paperclip tests 3-5x times.
module Paperclip
def self.run cmd, params = "", expected_outcodes = 0
cmd == 'convert' ? nil : super
end
end
class Paperclip::Attachment
def post_process
end
end
Paperclip > 3.5.2
For newer versions of Paperclip, use the following:
module Paperclip
def self.run cmd, arguments = "", interpolation_values = {}, local_options = {}
cmd == 'convert' ? nil : super
end
end
class Paperclip::Attachment
def post_process
end
end
I had a heckuva time dealing with this. I didn't want to test Paperclip per se -- rather, I needed a file to exist on my model so I can test a very sensitive custom class.
None of the other answers worked for me (Rails 5, Rspec 3.5) so I gave up on stubbing AWS or using the Paperclip::Shoulda::Matchers. Nothing worked and it ate up an entire day! Finally I gave up on Paperclip altogether and went this route:
list = build(:list)
allow(list).to receive_message_chain("file.url") { "#{Rails.root}/spec/fixtures/guess_fullname.csv" }
importer = Importer.new(list)
expect(importer.set_key_mapping).to eq({nil=>:email_address, :company=>:company, :fullname=>:full_name})
Where my models/list.rb has has_attached_file :file and Importer is a class I wrote that takes the file, which was already uploaded to S3 by paperclip before the class is initialized, and processes it. The file.url would otherwise be the S3 URL, so I give it the path in my repo to a testing csv file. set_key_mapping is a method in my class that I can use to verify the processing part worked.
Hope this saves somebody a few hours...
What about adding AWS.stub! in your spec/spec_helper.rb? Give that a try.
I'd like to create a general purpose string manipulation class that can be used across Models, Views, and Controllers in my Rails application.
Right now, I'm attempting to put a Module in my lib directory and I'm just trying to access the function in rails console to test it. I've tried a lot of the techniques from similar questions, but I can't get it to work.
In my lib/filenames.rb file:
module Filenames
def sanitize_filename(filename)
# Replace any non-letter or non-number character with a space
filename.gsub!(/[^A-Za-z0-9]+/, ' ')
#remove spaces from beginning and end
filename.strip!
#replaces spaces with hyphens
filename.gsub!(/\ +/, '-')
end
module_function :sanitize_filename
end
When I try to call sanitize_filename("some string"), I get a no method error. When I try to call Filenames.sanitize_filename("some string"), I get an uninitilized constant error. And when I try to include '/lib/filenames' I get a load error.
Is this the most conventional way to create a method that I can access anywhere? Should I create a class instead?
How can I get it working? :)
Thanks!
For a really great answer, look at Yehuda Katz' answer referenced in the comment to your question (and really, do look at that).
The short answer in this case is that you probably are not loading your file. See the link that RyanWilcox gave you. You can check this by putting a syntax error in your file - if the syntax error is not raised when starting your app (server or console), you know the file is not being loaded.
If you think you are loading it, please post the code you are using to load it. Again, see the link RyanWilcox gave you for details. It includes this code, which goes into one of your environment config files:
# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]
But really, read Yehuda's answer.
Are there any gems out there for Rails 3.2.1 that generate website thumbnails? I see a lot of 3rd party solutions but I don't like the fact that they aren't hosted on my server. It's really important the app I'm building is as stable as possible and I think this is not a good solution in the long run.
My ruby knowledge is fairly good, I think enough to use a gem and implement it, but definitely not good enough to write something like this from scratch if no gems exist.
Thanks!
You could try dragonfly or carrierwave
Well, here's the first thing that came up on Rubygems: thumbnailer. It uses Amazon and costs a small fee per image it generates, so you probably don't want this...
But there's also thumbnailer-ruby which looks like it works completely on the local machine. Haven't tested it out, though. It appears that this doesn't actually do what you want. Nevermind.
Now another gem called snapurl looks pretty fancy. Once again, I haven't tried it out yet. I'll do that now.
EDIT: Won't run for me; keeps failing with an error.
https://url2png.com/ has worked great so far
aBrowshot has a gem available.
There's no need to use a third party service for this.
You can do something like this in your model:
class MySexyModel < ActiveRecord::Base
... stuff
# Generate the thumbnail on validate so we can return errors on failure
validate :generate_thumbnail_from_url
# Cleanup temp files when we are done
after_save :cleanup_temp_thumbnail
# Generate a thumbnail from the remote URL
def generate_thumbnail_from_url
# Skip thumbnail generation if:
# a) there are already other validation errors
# b) an image was manually specified
# c) an image is already stored and the URL hasn't changed
skip_generate = self.errors.any? || (self.image_changed? ||
(self.image_stored? && !self.url_changed?))
# p "*** generating thumbnail: #{!skip_generate}"
return if skip_generate
# Generate and assign an image or set a validation error
begin
tempfile = temp_thumbnail_path
cmd = "wkhtmltoimage --quality 95 \"#{self.url}\" \"#{tempfile}\""
# p "*** grabbing thumbnail: #{cmd}"
system(cmd) # sometimes returns false even if image was saved
self.image = File.new(tempfile) # will throw if not saved
rescue => e
# p "*** thumbnail error: #{e}"
self.errors.add(:base, "Cannot generate thumbnail. Is your URL valid?")
ensure
end
end
# Return the absolute path to the temporary thumbnail file
def temp_thumbnail_path
File.expand_path("#{self.url.parameterize.slice(0, 20)}.jpg", Dragonfly.app.datastore.root_path)
end
# Cleanup the temporary thumbnail image
def cleanup_temp_thumbnail
File.delete(temp_thumbnail_path) rescue 0
end
end
The original post is on this blog: http://sourcey.com
I am working on an application where I use paperclip for uploading images, then the image is manipulated in a flash app and returned to my application using application/octet-stream. The problem is that the parameters from flash are not available using params. I have seen examples where something like
File.open(..,..) {|f| f.write(request.body) }
but when I do this, the file is damaged some how.
How can I handle this in rails 3?
After you make sure that the request parameters have hit the Rails application, you may want to ensure that there were no parsing problems. Try to add these lines in you controller's action:
def update # (or whatever)
logger.debug "params: #{params.inspect}"
# I hope you do not test this using very large files ;)
logger.debug "request.raw_post: #{request.raw_post.inspect}"
# ...
end
Maybe the variable names got changed somehow? Maybe something escaped the parameter string one time too much?
Also, you have said that the file into which you want to save the request body is damaged. How exactly?
The request.body object does not need to be String. It may be a StringIO, for example, so you may want to type this:
File.open(..,..) {|f| f.write(request.body.read) }