Image in asset pipeline not found - ruby-on-rails

I have seen a number of close problems, but have not been able to find a solution to get solve my problem. I am using Ruby 1.9.3 with Rails 3.2.13.
I am using Prawn to generate a PDF, and I a logo to appear. The logo is found without a problem in the development environment, but fails in the production environment, which is on Heroku.
In my controller I have:
def generate_risk_pdf(risk)
Prawn::Document.new do
image "#{Rails.root}/app/assets/images/logo-print.png", :scale => 0.75 if Rails.env.development?
image "#{ActionController::Base.helpers.asset_path('logo-print.png')}", :scale => 0.75 if Rails.env.production?
move_down 2
formatted_text [{:text => Exercise Australia", :styles => [:bold], :size => 20}]
font_size 6
bounding_box([bounds.right - 150, bounds.bottom], :width => 240, :height => 20) do
text "Copyright: Exercise Australia, #{Date.today.year}"
end
end.render
end
The Heroku logs have
ArgumentError (/assets/logo-print-5b6da7bd4012d953bc1bc749cf934d91.png not found):
app/controllers/single_entries_controller.rb:309:in `block in generate_risk_pdf'
Which corresponds to the line above with Rails.env.production?
If I append the URL to /assets/logo-print-5b6da7bd4012d953bc1bc749cf934d91.png the image file exists.
If I remove that line, it works (minus the logo).
Please note this is not only failing for Prawn, but even when I tried to use an image inline for an email.
Please help, I'm tearing my hair out!
Added: Serving from public works- but it is not my preferred solution.

Try add this to:
rails.root/config/environments/produciton.rb
config.serve_static_assets = true
config.assets.compile = true

A combination of both methods worked for me :
image "#{Rails.root}/app/assets#{ActionController::Base.helpers.asset_path('images/logo-print.png')}"

Related

rackspace private containers via fog gem

I'm looking for someone who can give me some tips - or, ideally, knows where to find a step-by-step guide or something - for working with private rackspace containers (via temp URL) using Fog in a Rails app. I've got fairly far using just their documentation, but none of the temp URLs I generate seem to be valid (401 errors).
Anyone have any tips? I know this is fairly vague, but was hoping there might be a comprehensive guide out there or something - wasn't able to find one via googling around.
Thanks!
EDITED
So in response to a comment, I tried following the directions from the getting started guide exactly. When I go to the URL returned by the code below, I get ERR_CONNECTION_REFUSED. Any ideas?
require "fog"
#storage = Fog::Storage.new(:rackspace_username => '{myUsername}',
:rackspace_api_key => '{myAPIKey}',
:rackspace_region => '{myRegion}',
:provider => 'Rackspace')
directory = #storage.directories.get('{myContainer}')
directory.public = false
directory.save
file = directory.files.create(
:key => 'somefile.txt',
:body => 'Rackspace is awesome!'
)
account = #storage.account
account.meta_temp_url_key = '{myTempUrlKey}'
account.save
#storage = Fog::Storage.new(:rackspace_username => '{myUsername}',
:rackspace_api_key => '{myAPIKey}',
:rackspace_region => '{myRegion}',
:rackspace_temp_url_key => '{myTempUrlKey}',
:provider => 'Rackspace')
directory = #storage.directories.get('{myContainer}')
file = directory.files.get('somefile.txt')
temp_url = file.url(Time.now.to_i + 1000000)
puts temp_url
SOLVED
By getting rid of the directory, file, and temp_url variables at the end and instead using
#storage.get_object_https_url('{myContainer}', 'somefile.txt', Time.now + 60)
which was found in the fog source here.

Paperclip not showing image even though URL/images in correct places

Using Paperclip to attach avatars to User profiles for my rails application. I followed the instructions on the paperclip github to initialize and attach to my app.
I have an image in the public/images/medium/missing.png and for both cases (when I upload or when I fallback on the default) I get no image. I've checked my directory and there is an image where it says it is looking but does not grab it. Additionally when I have tried uploading images, I know the image is uploaded correctly because when calling the User in rails console shows all the information properly attached.
I am calling the image in my view like:
<%= image_tag(#blog.user.avatar.url(":medium"), :class => "image-circle avatar") %>
my Paperclip declaration in the User model looks like the following:
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#"}, :default_url => "/public/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
Really not sure what is going on. The route errors that appear when I inspect the improperly loaded image point directly to the image in my local server. And the fact that it can't grab either the missing or the uploaded file also has me at a loss. Any help would be super appreciated!!
And for good measure the output when I examine a user with an uploaded avatar:
avatar_file_name: "11390219_10206114805925816_6595348111261743639_n.j...", avatar_content_type: "image/jpeg", avatar_file_size: 101926, avatar_updated_at: "2015-07-10 18:51:44">
Thanks in advance!
EDIT
This is the URL that is providing the 404 error:
http://localhost:3000/images/medium/missing.png
while in my local directory it goes "root/public/images/medium/missing.png"
not sure how its not grabbing it, unless I am just missing something really obvious somewhere. (i tried hard routing the public in there as well, but to no avail).
EDIT
There is the possibility that you're simply not serving the static assets, add:
config.serve_static_assets = true
to your development.rb
ORIGINAL POST
In you application.rb ( or an environment specific file ), you should have a config.paperclip_defaults = { ... }, here is the link in the docs: https://github.com/thoughtbot/paperclip#defaults
Here is an example one, using fog:
config.paperclip_defaults = {
:storage => :fog,
:fog_credentials => {
:provider => "Local",
:local_root => "#{Rails.root}/public"
},
:fog_directory => "",
:fog_host => "localhost:3000"
}
Do you have something like that in your application? I just tested on an app of mine, and I was able to upload an image, but not to see any without the paperclip_defaults hash. Also, don't forget to restart your app after you update the config files. I hope this helps!
Have you tried killing the quotes around the image style? Around :medium?
<%= image_tag(#blog.user.avatar.url(:medium), :class => "image-circle avatar") %>
As show here in the Paperclip Docs:
https://github.com/thoughtbot/paperclip#show-view
Same problem, solved it by reinstalling imagemagic with brew
Details: In case you're imagemagic, try to update the imagemagic and if it asks you to link it,
Try with this:
brew link --overwrite imagemagick
It worked for me. Hope its helpful

Paperclip don't generate styles and original image appears as broken

I having a big issue here. I really tried, but I can't solve this problem by myself, so I hope people can help me here.
Before talk about my problem, I must say I'm using Paperclip and IMGKit in my Project, but I think the problem is with Paperclip.
I create a Rails Task to take snapshots from the home page of some sites. Sometime ago everything is working fine, but now everything goes down. I import my real database from Heroku to localhost (without any images and migrations of paperclip), run the migrations, delete all old files from 'public/system' and run my task again (to take snapshot of all websites).
So, now I have:
The paths and original images are generated, but when I try to load them in View, this just show as a broken image.
Paperclip doesn't generate the path and converted images of :styles.
Sites that don't have image, I can see my default image correctly.
ImageMagick seems to be working, I try convert some images and worked like a charm.
Let's take a look at the code. Assume that I'm running a task that will perform this task to all sites in my database. The sites are called "items" in my architecture.
Development.rb
#config/environments/development.rb
# "which convert" give me this path
Paperclip.options[:command_path] = "/usr/local/bin/"
Item.rb (model)
My task just call "object.save" of every site in the DB, so my code starts on before_save.
has_attached_file :image,
:styles => { :small => "200x147#" },
:convert_options => { :small => "-quality 75 -strip" },
:default_url => '/images/:style/bitcoin-earth.jpg'
before_save :generate_data
def generate_data
self.image = get_image(self.id, self.url_original)
end
# Take snapshot of the website
def get_image(filename, link)
kit = IMGKit.new(link.to_s, :quality => 100, :width => 1024, :height => 768)
file = Tempfile.new(["template_#{filename}", 'png'], 'tmp',
:encoding => 'ascii-8bit')
file.write(kit.to_img(:png))
file.flush
return file
end
View
<%= image_tag store.image.url %>
Gemfile
gem "paperclip"
If I try to run rake paperclip:refresh:missing_styles, the task finish very fast without any error. But if I try to run rake paperclip:refresh CLASS=Item I got:
Image Paperclip::Errors::NotIdentifiedByImageMagickError
And yes, I already search for it and I didn't found a solution for my case.
A little tip?
When I "inspect element" in my project and try to see the source of the item image, I saw:
http://localhost:3000/public/system/items/images/000/000/216/original/template_21620140109-14507-1c0yszzpng?1389305824
But if I go to my project folder, I just see a image called template_21620140109-21209-1yls03opng. Note that doesn't exist any "?1389305824" there. See the image above.
Well, I think that's it. What can be the problem? I really need solve this issue, please, help me :/
[ Edited on Jan 10, 2013 ]
Item.rb (model):
before_save :generate_data
def generate_data
file = File.open(get_image(self.id, self.url_original))
self.image = file
file.close
end
def get_image(filename, link)
kit = IMGKit.new(link.to_s, :quality => 100,
:width => 1024, :height => 768)
file = Tempfile.new(["template_#{filename}", '.png'], 'tmp',
:encoding => 'ascii-8bit')
file.write(kit.to_img(:png))
file.flush
return file
end
Now I don't have any error on console while getting images and saving on DB, but Paperclip still don't generate my :styles. When I go to log/development.log, I can see this error, but I don't know what I can do to solve:
Command :: file -b --mime 'tmp/template_24320140110-17577-80zj1c.png'
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/template_24320140110-17577-80zj1c20140110-17577-mqa2q3.png[0]'
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
I think we're getting closer, please, keep helping me :)
I think your problem is here:
template_21620140109-14507-1c0yszzpng?1389305824 #-> should have .png (not a valid image)
Image
This might not be the problem, but maybe you could streamline your method to exclude the temporary file:
# Take snapshot of the website
def get_image(filename, link)
kit = IMGKit.new(link.to_s, :quality => 100, :width => 1024, :height => 768)
file = kit.to_file("system/temp/template_#{filename}")
return file
end
I think the issue is that ImageMagick is not being passed a "real" file, and consequently you're getting the unrecognized image issues

Rails why is this image not rendering (Rmagick, Heroku)

I have the following in my view:
<%= image_tag (url_for(:controller => 'app_images', :action => 'picture')) %>
The corresponding controller action is:
def picture
image = AppImage.create(:path => ("portrait3.jpeg"))
image.set_file_from_path
portrait = Magick::Image::from_blob(image.file)[0]
send_data portrait.to_blob, :type => "image/jpeg", :disposition => "inline"
end
And the model method for set_file_from_path is
def set_file_from_path
image = Magick::Image::from_blob(open(self.path).read)[0]
if image.rows > 400
resized = image.scale(400 * image.columns / image.rows, 400)
else
resized = image
end
self.file = resized.to_blob
end
For some reason, this image_tag doesn't render in Heroku, but renders locally, and I have the "portrait3.jpeg" file in my app/assets/images folder.
EDIT: I realized that I used create in heroku without actually connecting to S3 or anything else, which may not work as heroku doesn't allow for storage of a database on its servers I believe. I changed it to new and it still doesn't work.
So I did a few dumb things. Firstly, I forgot to require RMagick in the controller, and secondly I needed to do heroku run rake db:migrate.

Rails / Paperclip attaching via command line

I have a bunch of jpeg files in a folder on my server, and I'm attempting to attach them to their corresponding Property instances through a rake task.
property.rb has the following code:
has_attached_file :temp_photo,
:styles => PropertyImage::STYLES,
:url => "/assets/:class/:attachment/:id_partition/:style_:basename.:extension",
:path => "#{Rails.root}/public/assets/:class/:attachment/:id_partition/:style_:basename.:extension"
I use paperclip on other models, and there are no issues whatsoever, but I get a problem when I attempt the following:
p = Property.find(id)
file = File.open(temp_file_path)
p.temp_photo = file
p.save
# => false
file.close
p.errors
# => "/tmp/stream20110524-1126-1cunv0y-0.jpg is not recognized by the 'identify' command."
The file definitely exists, and I've tried changing the permissions. Restarting the server doesn't help. The problem seems to be with using the command line, as the normal form / HTTP approach works fine. This is only a temporary set-up, so I'm looking for a working way to import a batch of files into my rails app paperclip model.
Any suggestions?
path = 'target_file_path'
attach_name = 'temp_photo'
p = Property.find(id)
attach = Paperclip::Attachment.new(attach_name, p, p.class.attachment_definitions[attach_name.to_suym])
file = File.open(path)
attach.assign file
attach.save
file.close

Resources