Module: LooseChange::AttachmentClassMethods
- Included in:
- Base
- Defined in:
- lib/loose_change/attachments.rb
Instance Method Summary collapse
-
#attach(name, file, args = {}) ⇒ Object
Attach a file to this model, to be stored inline in CouchDB.
-
#attachment(name) ⇒ Object
Returns the file identified by
name
on a Loose Change model instance, whether or not that file has been saved back to CouchDB. -
#put_attachment(name) ⇒ Object
Explicitly transfers an attachment to CouchDB without saving the rest of the model.
-
#retrieve_attachment(name) ⇒ Object
Returns a hash composed of
file
andcontent_type
as returned from CouchDB identified byname
.
Instance Method Details
#attach(name, file, args = {}) ⇒ Object
Attach a file to this model, to be stored inline in CouchDB. Note that the file will not actually be transferred to CouchDB until #save is called. The name
parameter will be used on CouchDB and in Loose Change to retrieve the attachment later. If you set the :content_type
key in the optional args
hash, that content-type will be set on the attachment in CouchDB and available when the model is retrieved.
recipe = Recipe.create!(:name => "Lasagne")
recipe.attach(:photo, File.open("lasagne.png"), :content_type
=> 'image/png'
recipe.save
20 21 22 23 |
# File 'lib/loose_change/attachments.rb', line 20 def attach(name, file, args = {}) = args.merge :file => file, :dirty => true @attachments = (@attachments || {}).merge(name => ) end |
#attachment(name) ⇒ Object
Returns the file identified by name
on a Loose Change model instance, whether or not that file has been saved back to CouchDB. Will return nil if no attachment by that name exists.
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/loose_change/attachments.rb', line 28 def (name) name = name.to_s return [name][:file] if @attachments.try(:[], :name).try(:[], :file) begin result = (name) @attachments = (@attachments || {}).merge(name => {:file => result[:file], :dirty => false, :content_type => result[:content_type]}) result[:file] rescue RestClient::ResourceNotFound nil end end |
#put_attachment(name) ⇒ Object
Explicitly transfers an attachment to CouchDB without saving the rest of the model.
recipe.attach(:photo, File.open("lasagne.png"), :content_type
=> 'image/png'
recipe.put_attachment(:photo)
53 54 55 56 57 |
# File 'lib/loose_change/attachments.rb', line 53 def (name) return unless [name] result = JSON.parse(RestClient.put("#{ uri }/#{ CGI.escape(name) }#{ '?rev=' + @_rev if @_rev }", [name][:file], {:content_type => [name][:content_type], :accept => 'text/json'})) @_rev = result['rev'] end |
#retrieve_attachment(name) ⇒ Object
Returns a hash composed of file
and content_type
as returned from CouchDB identified by name
.
42 43 44 45 |
# File 'lib/loose_change/attachments.rb', line 42 def (name) { :file => RestClient.get("#{ uri }/#{ CGI.escape(name) }"), :content_type => JSON.parse(RestClient.get(uri))['_attachments']['name'] } end |