How does lambda function works in rails with an example from paperclip gem - ruby-on-rails

I had a problem with the Paperclip gem where the default_url doesn't load after it fingerprinted in production environment, my code was like this:
class User
# Attachments to Paperclip - Profile pic
has_attached_file :profilepic_attachment,
:styles => {
thumb: '100x100#',
square: '500x500#'
},
:default_url => ActionController::Base.helpers.asset_path("missing/default_user.png"),
:preserve_files => true
validates_attachment_content_type :profilepic_attachment, content_type: /\Aimage\/.*\Z/
end
Note that when I do rails c in production and print out ActionController::Base.helpers.asset_path("missing/default_user.png"). The fingerprinted version (correct version) is printed out.
default_user-fb34158daae99f297ad672c43bb1a4d3917d8e272b5f2254aa055392aa2faa94.png.
However, when I inspect it from browser, the original /assets/missing/default_user.png appeared.
I struggled for long time until I came across this post, which tells me to change
:default_url => ActionController::Base.helpers.asset_path("missing/default_user.png"),
to
:default_url => lambda { |image| ActionController::Base.helpers.asset_path("missing/default_user.png") },
I wasn't sure what happened, but then it works. I then wonder what lambda function is for and when is it used in rails? also, it passed in a variable |image| but seems it wasn't use in the code. Why is that?
Thanks!

Related

Adding Paperclip Attachment to Spree Orders Table,

I am working on an ecommerce website using Solidus, Rails. The site allows you to order photo frames & prints from a variety of options.
To print a photo a user must upload the jpg file of the photo. So, to allow that I modified the orders table and added a paperclip attachment called 'attachment'
I ran the following command
rails generate paperclip SpreeOrder attachment
Which generated the migrations, then I ran rake db:migrate
Then I created a spree/order_decorator.rb file, and added has_attached_file
module Spree::OrderDecorator
has_attached_file :attachment, styles: {
:medium => {
:geometry => "640x480",
:format => 'jpeg'
},
:thumb => { :geometry => "160x120", :format => 'jpeg', :time => 10}
}, :processors => [:transcoder]
validates_attachment_content_type :attachment, content_type: /\Aimage\/.*\z/
Spree::Order.prepend self
end
After this I ran the server, and ended up getting this error
undefined method `has_attached_file' for Spree::OrderDecorator:Module (NoMethodError)
I have configured solidus for use with paperclip only, so I am really confused as to why I am getting this error, even later I manually went and generated a paperclip.rb file in the config/initializers directory, but still I get the same error.
Please help with this!!
Thank You!!
You should add those paperclip method at class level in the prepended module:
def self.prepended(base)
base.has_attached_file
end

Getting URL for public assets in Rails model

I have a Rails application that uses Paperclip and saves images to S3. When the user uploads an asset without an image, it gets the default image set in the Paperclip setup.
My API serves those assets and has the links to the images in the JSON response (using jbuilder), however I can't seem to return the default image URL, it only returns "missing.png" and I wanted it to return the entire URL to the server with the missing image path attached to it.
I'm setting the default url in the model, and I've tried using ActionView::Helpers::AssetUrlHelper to get the image_url but it never works even though it is working inside the rails console. Any idea on what can I do to solve it?
The JBuilder file:
json.profile_picture_smallest asset.profile_picture.url(:smallest)
json.profile_picture_small asset.profile_picture.url(:small)
json.profile_picture_medium asset.profile_picture.url(:medium)
json.profile_picture_large asset.profile_picture.url(:large)
json.profile_picture_original asset.profile_picture.url(:original)
The part of paperclip that is included in the Model
module Picturable
extend ActiveSupport::Concern
included do
has_attached_file :profile_picture, path: '/images/' + name.downcase.pluralize + '/:style/:basename', default_url: "missing.png",
styles: {
smallest: '50x50>',
small: '100x100>',
medium: '200x200>',
large: '400x400>',
png: ['400x400>',:png]
}, :convert_options => {
smallest: '-trim',
small: '-trim',
medium: '-trim',
large: '-trim',
png: '-trim'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :profile_picture, :content_type => /\Aimage\/.*\Z/
end
def set_uuid_name
begin
self.profile_picture_file_name = SecureRandom.uuid
end while self.class.find_by(:profile_picture_file_name => self.profile_picture_file_name)
end
end
Paperclip config:
Paperclip::Attachment.default_options[:s3_host_name] = 's3hostname'
Development config:
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => 'paperclipdev',
:access_key_id => 'accesskey',
:secret_access_key => 'secretaccesskey'
}
}
I think the way to do this is use the asset helpers in your jbuilder file:
json.profile_picture_smallest asset_url(asset.profile_picture.url(:smallest))
It's worth a mention here that you can also pass a symbol method name to paperclip for the default_url parameter if you want the default url to be dynamic based on the model.

Getting correct path/url from Paperclip Gem during after_post_process callback?

I have a fairly standard Paperclip setup, it's almost straight out of the readme. I have a simple method triggered via callback to get the primary colors out of an uploaded image, and save them to the corresponding instance.
class Image < ActiveRecord::Base
has_attached_file :file, :styles => { large: "800x>", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :file, :content_type => /\Aimage\/.*\Z/
after_post_process :get_colors
def get_colors
colors = Miro::DominantColors.new(self.file.url)
colors = colors.to_hex.join(',')
self.colors = colors
self.save
end
end
As you can see, I have an after_post_process callback, and it does get triggered. The trouble is that when I call self.file.url I get a path that looks like this:
"/system/images/files//original/Peterson-Products-Wireframe-v01.jpg?1398443345".
It's missing the :id_partion portion. It's real path should look more like:
"/system/images/files/000/000/033/original/Peterson-Products-Wireframe-v01.jpg?1398443345"
Should I be using some other callback? I only want this triggered once per upload... Never again if the image is updated. Is this a bug in paperclip that I should be filing on Github?
Rails Version 4.1
Paperclip Version 4.1
Ruby 2.1.0
Thanks so much!
try queued_for_write
colors = Miro::DominantColors.new(file.queued_for_write[:original].path)

Ruby on Rails / Paperclip / AWS::S3::NoSuchBucket error

I installed the paperclip plugin and was able to use it locally. When I configured it to work with amazon S3 I keep getting the NoSuchBucket (The specified bucket does not exist) error. Paperclip documentation states that the bucket will be created if it doesn't exist but clearly
something is going wrong in my case.
I first insalled aws-s3 gem (v0.6.2)
then also installed right_aws gem (v1.9.0)
both have corresponding
config.gem "aws-s3", :lib => "aws/s3"
config.gem 'right_aws', :version => '1.9.0'
lines in environment.rb file
The code for the image.rb file with paperclip is as follows:
class Image < ActiveRecord::Base
belongs_to :work
has_attached_file :photo, :styles => {:big => "612x1224>", :small => "180X360>", :thumb => "36x36#"},
:storage => 's3',
:s3_credentials => YAML.load_file("#{RAILS_ROOT}/config/s3.yml")[RAILS_ENV],
:path => ":attachment/:id/:style/:basename.:extension",
:bucket => 'my-unique-image-bucket'
attr_protected :photo_file_name, :photo_content_type, :photo_size
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 3.megabytes
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png', 'image/gif']
end
I'm not entirely sure this is it, but your loading of the s3_credentials is different than what I'm using on my production sites.
My config line is:
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml"
Instead of
:s3_credentials => YAML.load_file("#{RAILS_ROOT}/config/s3.yml")[RAILS_ENV]
it should create but the bucket but this was a bug at one point :
http://groups.google.com/group/paperclip-plugin/browse_thread/thread/42f148cee71a0477
i recently had this problem and it turned out to be the servers time was hugely off and s3 wouldnt allow any updates "that far in the future" or similar but the rails error was NoSuchBucket...confusing
..
I have installed the s3fox plugin for firefox and created the bucket with the plugin. Now Paperclip works fine with S3 as the bucket identified is already created.
But I am still curious about paperclip's inability to create new buckets with the code above.
In case anyone winds up here via google: I saw this same error when I mistakenly switched the order of the 2nd and 3rd parameters I was passing to AWS::S3::S3Object.store.
It's not your case, but AWS doesn't allow upper case letters in bucket name and paperclip doesn't check that, failing in create_bucket.

Rails user-conditional statement in model

I'm working on a Rails app using attachment_ fu and Amazon S3 storage. Is it possible to make the :s3_ access (a part of the has_attachment options) conditional based on a user input when creating the object. I would like the user to be able if to select if the attachment is authenticated-read or public-read. Is this possible and how would you setup the conditional statement?
My model looks like this:
has_attachment :content_type => :image,
:storage => :s3,
:size => 0.kilobytes..6144.kilobytes,
:processor => 'Rmagick',
:resize_to => '650x500>',
:thumbnails => { :thumb => '75x75!' },
:s3_access => ( [[conditional]] ? 'authenticated-read' : 'public-read' )
Obviously [[conditional]] is what I'm looking to replace, but I don't know how to correctly setup a conditional for the item based off user action in the model. Maybe this is the wrong time of conditional for this type statement. Any suggestions?
James, I've done this before. I was digging through my old code, trying to find a sample I could show here, but I can't seem to find it. Old client, code is probably gone, etc...
You are on the right track though. Remember, 'has_attachment' is just a method call with a hash for the parameters, so if you treat it as such, you can adjust which hash values are ultimately sent to the method.
Edit - Here is a code sample -
production = ENV['RAILS_ENV'] == 'production'
has_attachment :content_type => :image,
:max_size => 1.megabyte,
:resize_to => '800x600>',
:thumbnails => { :thumb => '146x146>', :small => '75x75' },
# skip s3 for local development and testing
:storage => (production ? :s3 : :file_system),
:path_prefix => (production ? 'comment_images' : 'public/comment_images')
In the above example, I wanted to store uploads locally while developing, but switch to S3 when in production. So you are very close to where you need to be...

Resources