public
Created

Enable conditional default_url for Paperclip, to set default url with some method in the model

  • Download Gist
Readme
1
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
model.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
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
paper_clip_default_url_fix.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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

Know you how I can return :style too?

Like it:

  def set_picture_respect_to_gender
     self.gender? ? '/images/:style_male.jpg' : '/images/:style_female.jpg'
  end

Solved: Need to change paper_clip_default_url_fix.rb to this:

module Paperclip
  module Interpolations
    def self.interpolate pattern, *args
      pattern = args.first.instance.send(pattern) if pattern.kind_of? Symbol
      all.reverse.inject( pattern.dup ) do |result, tag|
        result.gsub(/:#{tag}/) do |match|
          send( tag, *args )
        end
      end
    end
  end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.