Module: Mongoid::Grid::ClassMethods

Defined in:
lib/mongoid/grid.rb

Instance Method Summary collapse

Instance Method Details

#attachment(name, prefix = 'grid') ⇒ Object

Declare an attachment for the object

eg: attachment :image



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
76
# File 'lib/mongoid/grid.rb', line 21

def attachment(name,prefix='grid')
  ##
  # Callbacks to handle the attachment saving and deleting
  after_save     :create_attachments
  after_save     :delete_attachments
  after_destroy  :destroy_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
  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
  
  ##
  # Returns true if attachment exists.
  # eg: image?
  define_method("#{name}?") do
    !!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
  
  ##
  # 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

#gridObject

Accessor to GridFS



80
81
82
# File 'lib/mongoid/grid.rb', line 80

def grid
  @grid ||= Mongo::Grid.new(Mongoid.database)
end