Class: CouchCrumbs::Database

Inherits:
Object
  • Object
show all
Includes:
Query
Defined in:
lib/couch_crumbs/database.rb

Overview

Direct representation of a CouchDB database (contains documents).

Constant Summary collapse

DEFAULT_NAME =
:couch_crumbs_database.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Query

#query_docs, #query_values

Constructor Details

#initialize(opts = {}) ⇒ Database

Get or create a database



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/couch_crumbs/database.rb', line 15

def initialize(opts = {})
  self.server = opts[:server] || CouchCrumbs::default_server
  self.name = (opts[:name] || DEFAULT_NAME).to_s
  self.uri = File.join(server.uri, self.name)

  begin
    self.status = RestClient.get(uri)
  rescue RestClient::ResourceNotFound
    RestClient.put(uri, "{}")
    retry
  end      
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



11
12
13
# File 'lib/couch_crumbs/database.rb', line 11

def name
  @name
end

#serverObject

Returns the value of attribute server.



11
12
13
# File 'lib/couch_crumbs/database.rb', line 11

def server
  @server
end

#statusObject

Returns the value of attribute status.



11
12
13
# File 'lib/couch_crumbs/database.rb', line 11

def status
  @status
end

#uriObject

Returns the value of attribute uri.



11
12
13
# File 'lib/couch_crumbs/database.rb', line 11

def uri
  @uri
end

Instance Method Details

#design_documentsObject

Return an array of only design documents



52
53
54
# File 'lib/couch_crumbs/database.rb', line 52

def design_documents
  documents(:startkey => "_design/")
end

#destroy!Object

Delete database from the server



58
59
60
61
62
63
64
# File 'lib/couch_crumbs/database.rb', line 58

def destroy!
  freeze
  
  result = JSON.parse(RestClient.delete(uri))
        
  result["ok"]
end

#documents(opts = {}) ⇒ Object

Return an array of all documents



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/couch_crumbs/database.rb', line 30

def documents(opts = {})
  # Query the special built-in _all_docs view
  query_docs(File.join(uri, "_all_docs"), opts).collect do |doc|
    # Regular documents
    if doc["crumb_type"]
      # Eval the class (with basic filtering, i.e. trusting your database)
      eval(doc["crumb_type"].gsub(/\W/i, '').capitalize!).get!(doc["_id"])
      
    elsif doc["_id"] =~ /^\_design\//
      # Design docs
      Design.get!(self, :id => doc["_id"])
    else
      # Ignore any other docs
      warn "skipping unknown document: #{ doc }"
      
      nil
    end
  end
end