Class: CouchDocs::DocumentDirectory

Inherits:
Object
  • Object
show all
Defined in:
lib/couch_docs/document_directory.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ DocumentDirectory

Returns a new instance of DocumentDirectory.



8
9
10
11
# File 'lib/couch_docs/document_directory.rb', line 8

def initialize(path)
  Dir.new(path)
  @couch_doc_dir = path
end

Instance Attribute Details

#couch_doc_dirObject

Returns the value of attribute couch_doc_dir.



6
7
8
# File 'lib/couch_docs/document_directory.rb', line 6

def couch_doc_dir
  @couch_doc_dir
end

Instance Method Details

#each_documentObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/couch_docs/document_directory.rb', line 13

def each_document
  Dir["#{couch_doc_dir}/*.json"].each do |filename|
    id = File.basename(filename, '.json')
    json = JSON.parse(File.new(filename).read)

    if File.directory? "#{couch_doc_dir}/#{id}"
      json["_attachments"] ||= { }
      Dir["#{couch_doc_dir}/#{id}/*"].each do |attachment|
        next unless File.file? attachment
        attachment_name = File.basename(attachment)
        json["_attachments"][attachment_name] = file_as_attachment(attachment)
      end
    end

    yield [ id, json ]
  end
end

#file_as_attachment(file) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/couch_docs/document_directory.rb', line 38

def file_as_attachment(file)
  type = mime_type(file)
  data = File.read(file)

  attachment =  {
    "data" => Base64.encode64(data).gsub(/\n/, '')
  }
  if type
    attachment.merge!({"content_type" => type})
  end

  attachment
end

#make_attachment_dir(id) ⇒ Object



61
62
63
# File 'lib/couch_docs/document_directory.rb', line 61

def make_attachment_dir(id)
  FileUtils.mkdir_p "#{couch_doc_dir}/#{id}"
end

#save_attachment(id, filename, data) ⇒ Object



65
66
67
68
69
# File 'lib/couch_docs/document_directory.rb', line 65

def save_attachment(id, filename, data)
  file = File.new "#{couch_doc_dir}/#{id}/#{filename}", "w"
  file.write Base64.decode64(data)
  file.close
end

#store_attachments(id, attachments) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/couch_docs/document_directory.rb', line 52

def store_attachments(id, attachments)
  return unless attachments

  make_attachment_dir(id)
  attachments.each do |filename, opts|
    save_attachment(id, filename, opts['data'])
  end
end

#store_document(doc) ⇒ Object



31
32
33
34
35
36
# File 'lib/couch_docs/document_directory.rb', line 31

def store_document(doc)
  file = File.new("#{couch_doc_dir}/#{doc['_id']}.json", "w+")
  store_attachments(doc['_id'], doc.delete('_attachments'))
  file.write(doc.to_json)
  file.close
end