merged in changes from live version
[selectricity-live] / vendor / plugins / attachment_fu / lib / technoweenie / attachment_fu / backends / db_file_backend.rb
1 module Technoweenie # :nodoc:
2   module AttachmentFu # :nodoc:
3     module Backends
4       # Methods for DB backed attachments
5       module DbFileBackend
6         def self.included(base) #:nodoc:
7           Object.const_set(:DbFile, Class.new(ActiveRecord::Base)) unless Object.const_defined?(:DbFile)
8           base.belongs_to  :db_file, :class_name => '::DbFile', :foreign_key => 'db_file_id'
9         end
10
11         # Creates a temp file with the current db data.
12         def create_temp_file
13           write_to_temp_file current_data
14         end
15         
16         # Gets the current data from the database
17         def current_data
18           db_file.data
19         end
20         
21         protected
22           # Destroys the file.  Called in the after_destroy callback
23           def destroy_file
24             db_file.destroy if db_file
25           end
26           
27           # Saves the data to the DbFile model
28           def save_to_storage
29             if save_attachment?
30               (db_file || build_db_file).data = temp_data
31               db_file.save!
32               self.class.update_all ['db_file_id = ?', self.db_file_id = db_file.id], ['id = ?', id]
33             end
34             true
35           end
36       end
37     end
38   end
39 end

Benjamin Mako Hill || Want to submit a patch?