Skip to content

Instantly share code, notes, and snippets.

@anoras
Forked from anlek/mongo_paperclip.rb
Created August 3, 2010 12:14
Show Gist options
  • Save anoras/506260 to your computer and use it in GitHub Desktop.
Save anoras/506260 to your computer and use it in GitHub Desktop.
Patching Paperclip to work with MongoMapper
module Paperclip
class << self
def logger #:nodoc:
# Paperclip depends on having a logger available, so let's create a nice fallback chain...
MongoMapper.logger || Rails.logger || Logger.new(STDOUT)
end
end
module ClassMethods
def has_attached_file name, options = {}
include InstanceMethods
# Create keys to store Paperclip's metadata
key :"#{name}_file_name", String
key :"#{name}_content_type", String
key :"#{name}_file_size", String
key :"#{name}_updated_at", DateTime
write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
attachment_definitions[name] = {:validations => []}.merge(options)
after_save :save_attached_files
before_destroy :destroy_attached_files
define_callbacks :before_post_process, :after_post_process
define_callbacks :"before_#{name}_post_process", :"after_#{name}_post_process"
define_method name do |*args|
a = attachment_for(name)
(args.length > 0) ? a.to_s(args.first) : a
end
define_method "#{name}=" do |file|
attachment_for(name).assign(file)
end
define_method "#{name}?" do
attachment_for(name).file?
end
validates_each name, :logic => lambda {|record, attr, value|
attachment = record.attachment_for(name)
attachment.send(:flush_errors) unless attachment.valid?
}
end
end
module Interpolations
# Handle string ids (mongo)
def id_partition attachment, style
if (id = attachment.instance.id).is_a?(Integer)
("%09d" % id).scan(/\d{3}/).join("/")
else
id.scan(/.{3}/).first(3).join("/")
end
end
end
class Attachment
# Somehow the :updated_at field gets returned as Date even if its key is a DateTime or Time...
def updated_at
time = instance_read(:updated_at).to_time
time && time.to_f.to_i
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment