Module: Mongoid::Grid::ClassMethods
- Defined in:
- lib/mongoid_grid.rb
Instance Method Summary collapse
-
#attachment(name, prefix = 'grid') ⇒ Object
Declare an attachment for the object.
-
#attachment_types ⇒ Object
All the attachments types for this class.
-
#grid ⇒ Object
Accessor to GridFS.
Instance Method Details
#attachment(name, prefix = 'grid') ⇒ Object
Declare an attachment for the object
eg: attachment :image
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/mongoid_grid.rb', line 16 def (name,prefix='grid') ## # Callbacks to handle the attachment saving and deleting after_save :create_attachments after_save :delete_attachments after_destroy :destroy_attachments, :delete_attachments ## # Fields for the attachment. # # Only the _id is really needed, the others are helpful cached # so you don't need to hit GridFS field "#{name}_id".to_sym, :type => BSON::ObjectId field "#{name}_name".to_sym, :type => String field "#{name}_size".to_sym, :type => Integer field "#{name}_type".to_sym, :type => String ## # Add this name to the attachment_types .push(name).uniq! ## # Return the GridFS object. # eg: image.filename, image.read define_method(name) do grid.get(attributes["#{name}_id"]) if attributes["#{name}_id"] end ## # Create a method to set the attachment # eg: object.image = File.open('/tmp/somefile.jpg') define_method("#{name}=") do |file| if file.respond_to?(:read) send(:create_attachment, name, file) else send(:delete_attachment, name, send("#{name}_id")) end end ## # Create a method to set the attachment for binary string. # eg: object.set_image(binary_string, "generated_filename.png") define_method("set_#{name}") do |binary, filename| if !binary.nil? send(:create_attachment_raw, name, binary, filename) else send(:delete_attachment, name, send("#{name}_id")) end end ## # Return the relative URL to the file for use with Rack::Grid # eg: /grid/4ba69fde8c8f369a6e000003/somefile.png define_method("#{name}_url") do _id = send("#{name}_id") _name = send("#{name}_name") ["/#{prefix}", _id, _name].join('/') if _id && _name end end |
#attachment_types ⇒ Object
All the attachments types for this class
85 86 87 |
# File 'lib/mongoid_grid.rb', line 85 def ||= [] end |
#grid ⇒ Object
Accessor to GridFS
79 80 81 |
# File 'lib/mongoid_grid.rb', line 79 def grid @grid ||= Mongo::Grid.new(Mongoid.database) end |