Module: Exegesis::Database::InstanceMethods

Defined in:
lib/exegesis/database.rb

Instance Method Summary collapse

Instance Method Details

#get(id, opts = {}) ⇒ Object

GETs a document with the given id from the database



76
77
78
# File 'lib/exegesis/database.rb', line 76

def get id, opts={}
  Exegesis.instantiate raw_get(id), self
end

#initialize(server, database_name = nil) ⇒ Object

Create a Database adapter for the given server and database name. Will raise RestClient::ResourceNotFound if the database does not exist.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/exegesis/database.rb', line 47

def initialize server, database_name=nil
  if database_name.nil?
    if server.match(/\A(https?:\/\/[-0-9a-z\.]+(?::\d+))\/(#{Exegesis::Database::VALID_NAME_PATTERN})\Z/)
      @server = Exegesis::Server.new($1)
      database_name = $2
    elsif server.match(/\A#{Exegesis::Database::VALID_NAME_PATTERN}\Z/)
      @server = Exegesis::Server.new #localhost
      database_name = server
    else
      raise "Not a valid database url or name"
    end
  else
    @server = server
  end
  @uri = "#{@server.uri}/#{database_name}"
  @server.get @uri # raise RestClient::ResourceNotFound if the database does not exist
end

#post(url, body = {}) ⇒ Object

POSTs the body to the database



100
101
102
103
104
105
106
# File 'lib/exegesis/database.rb', line 100

def post url, body={}
  if body.is_a?(Hash) && body.empty?
    body = url
    url = ''
  end
  Exegesis::Http.post "#{@uri}/#{url}", body
end

#put(id, body) ⇒ Object

PUTs the body to the given id in the database



95
96
97
# File 'lib/exegesis/database.rb', line 95

def put id, body
  Exegesis::Http.put "#{@uri}/#{id}", body
end

#raw_get(id, options = {}) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/exegesis/database.rb', line 65

def raw_get id, options={}
  keys = options.delete(:keys)
  url = Exegesis::Http.format_url "#{@uri}/#{id}", options
  if id.match(%r{^_design/.*/_view/.*$}) && keys
    Exegesis::Http.post url, {:keys => keys}
  else
    Exegesis::Http.get url
  end
end

#save(docs) ⇒ Object

saves a document or collection thereof



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/exegesis/database.rb', line 81

def save docs
  if docs.is_a?(Array)
    post "_bulk_docs", { 'docs' => docs }
  else
    result = docs['_id'].nil? ? post(docs) : put(docs['_id'], docs)
    if result['ok']
      docs['_id'] = result['id']
      docs['_rev'] = result['rev']
    end
    docs
  end
end