views:

24

answers:

2

Hi,

I've been breaking the DRY principle a bit in a project built with Paperclip for media storage. I've added assets to certain models, such as AlbumPhotoFile, AlbumSoundFile and so on, using the following code :

# Asset is a regular < ActiveRecord::Base class 
class AlbumPhotoFile < Asset
  has_attached_file :pic, :url => "foo", :path => "bar"
  validates_attachment_presence :pic, :message => "can't be blank"
  validates_attachment_content_type :pic, :content_type => ["foo", "bar"]
end

Scaling to some more requirements, I had to attach photos to other models, say CityPhotoFile. I want to keep the validations and has_attached_file fu the same as in other PhotoFile-type models. I have just copy-pasted the code from a PhotoFile model to the other, is there a better method for that ?

There aren't any Paperclip-related errors, the storage and display works fine, I just wanted to know if this type of operation can be put in a module or something like that, for DRY's sake.

Just bouncing off the code is really getting ugly. I can provide more details if I haven't made my intentions clear in this space :-).

Thank you in advance !

+1  A: 

Yeah, you could move that code out into a module, then include it in your class as follows:

# in lib/default_paperclip
module DefaultPaperclip
  has_attached_file :pic, :url => "foo", :path => "bar"
  validates_attachment_presence :pic, :message => "can't be blank"
  validates_attachment_content_type :pic, :content_type => ["foo", "bar"]
end


# your active record
class AlbumPhotoFile < ActiveRecord::Base
  include DefaultPaperclip
end

Think that should work. Not tested though!

Mr. Matt
I'll try it out when I get back to work, thank you for the input !
Dr1Ku
Some more Module stuff had to be included as well, I've included the working solution below. Thank you for your input !
Dr1Ku
+1  A: 

Here's what worked for me, based on Mr.Matt's solution :

# in lib/paperclip_template_audio.rb, for instance
module PaperclipTemplateAudio

  # Stuff directives into including module
  def self.included(recipient)
    recipient.class_eval do
      has_attached_file :pic, :url => "foo", :path => "bar"
      validates_attachment_presence :pic, :message => "can't be blank"
      validates_attachment_content_type :pic, :content_type => ["foo", "bar"]
    end
  end

end # Module

In my model :

class AlbumPhotoFile < ActiveRecord::Base
  include PaperclipTemplateAudio
end
Dr1Ku