Custom validation with Paperclip

Posted by andy

In my rails apps I used to use attachment_fu for uploading files, but of late I have moved over to thoughtbots Paperclip plugin. Its perfect for most instances, and indeed simple to use. I required it to do a little more than it can do out of the box. In my case I needed to check that the uploaded document was a well formed XML document. The result was a nice little custom validation method levered into the plugin.

# lib/paperclip_mixin.rb
module Paperclip
  module ClassMethods
    def validates_attachment_valid_xml name
       require 'xml/libxml'
       @attachment_definitions[name][:validations] << lambda do |attachment, instance|
         if attachment.file.nil? || !File.exist?(attachment.file.path)
           "must be set" 
         else
         # check file is valid xml
           begin
             # use libxml-ruby gem to do basic check on the file
             parser = XML::Parser.new
             parser.string = File.open(attachment.file.path).read
             parser.parse
             return nil # i.e no exceptions equals validity
           rescue
             "must be a valid xml document" 
           end
         end
       end
     end
  end
end

Then initiallise this patch it in our initializers.

# config/initializers/custom_requires.rb
require 'paperclip_mixin'

Now we can just add this validation method to our model that is using paperclip

# app/models/asset.rb
class Asset < ActiveRecord::Base
  has_attached_file :config_file
  validates_attachment_valid_xml :config_file
end

And that worked fine. yay.

Comments

Leave a response