Created
June 22, 2011 13:29
-
-
Save nazarhussain/1040091 to your computer and use it in GitHub Desktop.
Enable conditional default_url for Paperclip, to set default url with some method in the model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In some cases you need to set the default_url of paper clip base on some condition. e.g. You want to set default image on basis of gender of user. For this purpose this gist can make it possible to use a method as default_url. Just copy paper_clip_default_url_fix.rb to initializers folder, and use default_url as mentioned in model.rb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
def set_picture_respect_to_gender | |
self.gender? ? '/images/male.jpg' : '/images/female.jpg' | |
end | |
has_attached_file :display_picture, | |
:styles => { :medium => "150x150>", :thumb => "100x100>", :small => "50x50>" }, | |
:url => "/system/user/:id/:attachment/:style/:basename.:extension" | |
:default_url => :set_picture_respect_to_gender | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Paperclip | |
module Interpolations | |
def self.interpolate pattern, *args | |
if pattern.kind_of? Symbol | |
args.first.instance.send(pattern) | |
else | |
all.reverse.inject( pattern.dup ) do |result, tag| | |
result.gsub(/:#{tag}/) do |match| | |
send( tag, *args ) | |
end | |
end | |
end | |
end | |
end | |
end |
I know it's outdated as hell, but if anyone is still here - BE CAREFUL WITH THIS CODE! It slows down the code A LOT, especially if you need to get many image urls on the same page.
@AvaelKross Yes its about 8 year old code and I am not sure if its valid any more. But for clarity reasons can you pin-point exactly what code slows down? It slows down the startup or a request cycle?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solved: Need to change
paper_clip_default_url_fix.rb
to this: