Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Paperclip, DRY configuration

In order to DRY up my code for attachments pictures, I created an initializer to override the @default_options variable used by Paperclip.

This way, I don't have to specify again and again the url, path and storage I want.

I'd like to go a step further and include the validation in it but I can't make it work...

Any Idea?

EDIT 1: I want at least to validate both presence and size.

EDIT 2: Part of my current code

module Paperclip
 class Attachment
   def self.default_options
     if Rails.env != "production"
       @default_options = {
         :url => "/assets/:class/:attachment/:id/:style/:normalized_name",
         :path => ":rails_root/public/assets/:class/:attachment/:id/:style/:normalized_name",
         :default_style => :original,
         :storage       => :filesystem,
         :whiny         => Paperclip.options[:whiny] || Paperclip.options[:whiny_thumbnails]
         }
      else
       ...
      end
   end
 end

normalized_name is an outside function, feat: http://blog.wyeworks.com/2009/7/13/paperclip-file-rename

EDIT 3:

This blog: http://omgsean.com/2009/02/overriding-paperclip-defaults-for-your-entire-rails-app/ presnents the default_options hash with a validations key.

So it could be possible, not found yet though.

like image 855
apneadiving Avatar asked Jan 31 '26 19:01

apneadiving


1 Answers

You will not be able to move the validations into a default_options hash (as these validations are performed outside the attachment class (inside a paperclip module). My thought is that if you have the same validations across all your models, you might need to look into using inheritance to decrease code duplication. I would advise against moving validations into an initializer.

like image 168
Kevin Sylvestre Avatar answered Feb 02 '26 10:02

Kevin Sylvestre