Class: Armchair

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/armchair.rb

Overview

An Armchair is very a minimal interface to a CouchDB database. It is Enumarable.

Instance Method Summary collapse

Constructor Details

#initialize(dburl, batch_size = 100) ⇒ Armchair

Pass in the database url and optionally a batch_size which is used when iterating over the armchair in Armchair#each

couch = Armchair.new 'http://127.0.0.1:5984/mycouch'


12
13
14
15
# File 'lib/armchair.rb', line 12

def initialize dburl, batch_size = 100
  @dburl = dburl.gsub(/\/$/,'')
  @batch_size = batch_size
end

Instance Method Details

#<<(doc) ⇒ Object

Shift a document into the Armchair. doc should be a Hash.

armchair << { 'a' => 'document' } << { 'another' => 'document' }


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

def << doc
  RestClient.post @dburl, JSON(doc), :content_type => :json, :accept => :json do |response|
    response.return! unless response.code == 201
  end
  self
end

#create!Object

Create the CouchDB database at dburl (see Armchair#new) if it does not exist yet



18
19
20
21
22
23
24
25
26
27
# File 'lib/armchair.rb', line 18

def create!
  RestClient.get @dburl, :accept => :json do |response|
    case response.code
    when 404
      RestClient.put @dburl, nil, :content_type => :json, :accept => :json
    else
      response.return!
    end
  end
end

#eachObject

yields each document



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/armchair.rb', line 51

def each
  # iterate in batches of @batch_size
  # initial query
  res = RestClient.get(@dburl + "/_all_docs?limit=#{@batch_size+1}&include_docs=true", :accept => :json) do |r|
    case r.code
    when 200
      JSON(r.body)
    else
      r.return!
    end
  end
  rows = res['rows']
  last = rows.size > @batch_size ? rows.pop : nil
  rows.each { |row| doc = row['doc']; yield doc }
  # subsequent queries
  while last
    startkey = last['key']
    res = RestClient.get(@dburl + "/_all_docs?startkey=%22#{startkey}%22&limit=#{@batch_size+1}&include_docs=true", :accept => :json) do |r|
      case r.code
      when 200
        JSON(r.body)
      else
        r.return!
      end
    end
    rows = res['rows']
    last = rows.size > @batch_size ? rows.pop : nil
    rows.each { |row| yield row['doc'] }
  end
end

#sizeObject

Returns the size of the Armchair (the number of documents stored).



39
40
41
42
43
44
45
46
47
48
# File 'lib/armchair.rb', line 39

def size
  RestClient.get(@dburl + '/_all_docs?limit=0', :accept => :json) do |r|
    case r.code
    when 200
      JSON(r.body)['total_rows']
    else
      r.return!
    end
  end
end