Class: CouchDocument

Inherits:
CouchIO show all
Defined in:
lib/couchio/couch_document.rb

Instance Attribute Summary

Attributes inherited from CouchIO

#append, #path, #readable, #writeable

Instance Method Summary collapse

Methods inherited from CouchIO

#initialize

Constructor Details

This class inherits a constructor from CouchIO

Instance Method Details

#closeObject



2
3
4
# File 'lib/couchio/couch_document.rb', line 2

def close
  save
end

#printf(data, *args) ⇒ Object



33
34
35
# File 'lib/couchio/couch_document.rb', line 33

def printf(data, *args)
  write_string sprintf(data, *args)
end

#readObject



6
7
8
9
10
11
12
13
14
# File 'lib/couchio/couch_document.rb', line 6

def read
  return @local_copy if @dirty
    
  json = read_json
  verify_ok(json)
  @local_copy = json
rescue Errno::ENOENT
  @local_copy = {'_id' => File.basename(path)}
end

#write(data) ⇒ Object Also known as: print



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/couchio/couch_document.rb', line 16

def write(data)
  read if !@local_copy
  if @local_copy.is_a?(Hash)
    @local_copy.delete_if {|k,v| !append && k[0,1] != '_' }
  end
    
  if data.is_a?(String) 
    write_string(data)
  elsif data.is_a?(Hash)
    write_hash(data)
  else
    raise ArgumentError, "expecting String or Hash, got #{data.class}"
  end
  @dirty = true
end

#write_hash(data) ⇒ Object



57
58
59
60
# File 'lib/couchio/couch_document.rb', line 57

def write_hash(data)
  data = data.stringify_keys
  @local_copy.update(data)
end

#write_string(data) ⇒ Object Also known as: puts



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/couchio/couch_document.rb', line 37

def write_string(data)
  CouchDocument.new(File.dirname(path), 'a') do |f|
    item = f.read
    item['_attachments'] ||= {}
    
    if append && item['_attachments'][File.basename(path)]
      item['_attachments'][File.basename(path)].update({
        'data' => Base64.b64encode(read.to_s + data.to_s).chomp
      })
    else
      item['_attachments'].update(File.basename(path) => {
        'content_type' => 'text/plain',
        'data' => Base64.b64encode(data).chomp
      })
    end
    f.write(item)
  end
end