Module: SimplyCouch::Model::Attachments

Defined in:
lib/simply_couch/model/attachments.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



21
22
23
# File 'lib/simply_couch/model/attachments.rb', line 21

def self.included(base)
  base.after_save :_save_pending_attachments
end

Instance Method Details

#add_attachment(name, file, content_type: 'binary/octet-stream') ⇒ Object

Queue an attachment for upload on next save. Useful when building a new document that hasn’t been saved yet (no _rev available for immediate put_attachment).



47
48
49
50
# File 'lib/simply_couch/model/attachments.rb', line 47

def add_attachment(name, file, content_type: 'binary/octet-stream')
  @_pending_attachments ||= {}
  @_pending_attachments[name] = { file: file, content_type: content_type }
end

#attachment?(name) ⇒ Boolean

Check if an attachment exists.

Returns:

  • (Boolean)


66
67
68
# File 'lib/simply_couch/model/attachments.rb', line 66

def attachment?(name)
  attachment_names.include?(name.to_s)
end

#attachment_namesObject

List all attachment names on this document.



61
62
63
# File 'lib/simply_couch/model/attachments.rb', line 61

def attachment_names
  (_attachments || {}).keys
end

#delete_attachment(name) ⇒ Object

Delete an attachment from this document. The attachment is removed immediately — no need to call save separately.



54
55
56
57
58
# File 'lib/simply_couch/model/attachments.rb', line 54

def delete_attachment(name)
  result = _couchrest_database.delete_attachment(to_hash, name)
  self._rev = result['rev'] if result['ok']
  result
end

#fetch_attachment(name) ⇒ Object

Fetch an attachment’s binary data from CouchDB. Returns nil if the attachment doesn’t exist.



38
39
40
41
42
# File 'lib/simply_couch/model/attachments.rb', line 38

def fetch_attachment(name)
  _couchrest_database.fetch_attachment(to_hash, name)
rescue RestClient::ResourceNotFound
  nil
end

#put_attachment(name, file, content_type: 'binary/octet-stream') ⇒ Object

Upload a file as a CouchDB inline attachment on this document. The attachment is stored immediately — no need to call save separately. Returns the CouchDB result hash.



28
29
30
31
32
33
34
# File 'lib/simply_couch/model/attachments.rb', line 28

def put_attachment(name, file, content_type: 'binary/octet-stream')
  result = _couchrest_database.put_attachment(
    to_hash, name, file, content_type: content_type
  )
  self._rev = result['rev'] if result['ok']
  result
end