Class: Rufus::Jig::Couch

Inherits:
Object
  • Object
show all
Defined in:
lib/rufus/jig/couch.rb

Overview

A class wrapping an instance of Rufus::Jig::Http and providing CouchDB-oriented http verbs.

Constant Summary collapse

DESIGN_PATH_REGEX =
/^\_design\//

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Couch

Returns a new instance of Couch.



43
44
45
46
47
48
# File 'lib/rufus/jig/couch.rb', line 43

def initialize(*args)

  @http = Rufus::Jig::Http.new(*args)

  @path = @http._path || '/'
end

Instance Attribute Details

#http ⇒ Object (readonly)

Returns the value of attribute http.



41
42
43
# File 'lib/rufus/jig/couch.rb', line 41

def http
  @http
end

#path ⇒ Object (readonly)

Returns the value of attribute path.



40
41
42
# File 'lib/rufus/jig/couch.rb', line 40

def path
  @path
end

Instance Method Details

#all(opts = {}) ⇒ Object

Returns all the docs in the current database.

c = Rufus::Jig::Couch.new('http://127.0.0.1:5984, 'my_db')

docs = c.all
docs = c.all(:include_docs => false)
docs = c.all(:include_design_docs => false)

docs = c.all(:skip => 10, :limit => 10)

It understands (passes) all the options for CouchDB view API :

http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options


111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/rufus/jig/couch.rb', line 111

def all(opts={})

  opts = opts.dup
    # don't touch the original

  path = adjust('_all_docs')

  opts[:include_docs] = true if opts[:include_docs].nil?

  adjust_params(opts)

  keys = opts.delete(:keys)

  return [] if keys && keys.empty?

  res = if keys
    opts[:cache] = :with_body if opts[:cache].nil?
    @http.post(path, { 'keys' => keys }, opts)
  else
    @http.get(path, opts)
  end

  rows = res['rows']

  docs = if opts[:params][:include_docs]
    rows.map { |row| row['doc'] }
  else
    rows.map { |row| { '_id' => row['id'], '_rev' => row['value']['rev'] } }
  end

  if opts[:include_design_docs] == false
    docs = docs.reject { |doc| DESIGN_PATH_REGEX.match(doc['_id']) }
  end

  docs
end

#attach(doc_id, doc_rev, attachment_name, data, opts = nil) ⇒ Object

Attaches a file to a couch document.

couch.attach(
doc['_id'], doc['_rev'], 'my_picture', data,
:content_type => 'image/jpeg')

or

couch.attach(
doc, 'my_picture', data,
:content_type => 'image/jpeg')

Raises:

  • (ArgumentError)


209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/rufus/jig/couch.rb', line 209

def attach(doc_id, doc_rev, attachment_name, data, opts=nil)

  if opts.nil?
    opts = data
    data = attachment_name
    attachment_name = doc_rev
    doc_rev = doc_id['_rev']
    doc_id = doc_id['_id']
  end

  attachment_name = attachment_name.gsub(/\//, '%2F')

  ct = opts[:content_type]

  raise(ArgumentError.new(
    ":content_type option must be specified"
  )) unless ct

  opts[:cache] = false

  path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")

  if @http.variant == :patron

    # patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting
    # attachements
    # this is a fallback to net/http

    require 'net/http'

    http = Net::HTTP.new(@http.host, @http.port)

    req = Net::HTTP::Put.new(path)
    req['User-Agent'] =
      "rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)"
    req['Content-Type'] =
      opts[:content_type]
    req['Accept'] =
      'application/json'
    req.body = data

    res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) })

    return @http.send(:respond, :put, path, nil, opts, nil, res)
  end

  @http.put(path, data, opts)
end

#bulk_delete(docs, opts = {}) ⇒ Object

Given an array of documents (at least { '_id' => x, '_rev' => y }, deletes them.



454
455
456
457
458
459
460
461
462
463
464
# File 'lib/rufus/jig/couch.rb', line 454

def bulk_delete(docs, opts={})

  docs = docs.inject([]) { |a, doc|
    a << {
      '_id' => doc['_id'], '_rev' => doc['_rev'], '_deleted' => true
    } if doc
    a
  }

  bulk_put(docs, opts)
end

#bulk_put(docs, opts = {}) ⇒ Object



442
443
444
445
446
447
448
449
# File 'lib/rufus/jig/couch.rb', line 442

def bulk_put(docs, opts={})

  res = @http.post(adjust('_bulk_docs'), { 'docs' => docs })

  opts[:raw] ?
    res :
    res.collect { |row| { '_id' => row['id'], '_rev' => row['rev'] } }
end

#close ⇒ Object



55
56
57
58
# File 'lib/rufus/jig/couch.rb', line 55

def close

  @http.close
end

#delete(doc_or_path, rev = nil) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/rufus/jig/couch.rb', line 153

def delete(doc_or_path, rev=nil)

  doc, path = if rev
    [ { '_id' => doc_or_path, '_rev' => rev }, doc_or_path ]
  elsif doc_or_path.is_a?(String)
    [ nil, doc_or_path ]
  else
    [ doc_or_path, doc_or_path['_id'] ]
  end

  path = adjust(path)

  r = if doc

    raise(
      ArgumentError.new("cannot delete document without _rev")
    ) unless doc['_rev']

    rpath = Rufus::Jig::Path.add_params(path, :rev => doc['_rev'])

    @http.delete(rpath)

  else

    @http.delete(path)
  end

  if r == true # conflict

    doc = @http.get(path)
    doc ? doc : true
      # returns the doc if present or true if the doc is gone

  else # delete is successful

    nil
  end
end

#detach(doc_id, doc_rev, attachment_name = nil) ⇒ Object

Detaches a file from a couch document.

couch.detach(doc['_id'], doc['_rev'], 'my_picture')

or

couch.detach(doc, 'my_picture')


266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/rufus/jig/couch.rb', line 266

def detach(doc_id, doc_rev, attachment_name=nil)

  if attachment_name.nil?
    attachment_name = doc_rev
    doc_rev = doc_id['_rev']
    doc_id = doc_id['_id']
  end

  attachment_name = attachment_name.gsub(/\//, '%2F')

  path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")

  @http.delete(path)
end

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



89
90
91
92
93
94
95
# File 'lib/rufus/jig/couch.rb', line 89

def get(doc_or_path, opts={})

  path = doc_or_path.is_a?(Hash) ? doc_or_path['_id'] : doc_or_path
  path = adjust(path)

  @http.get(path, opts)
end

#ids(opts = {}) ⇒ Object



148
149
150
151
# File 'lib/rufus/jig/couch.rb', line 148

def ids(opts={})

  all(opts).collect { |row| row['_id'] }
end

#name ⇒ Object



50
51
52
53
# File 'lib/rufus/jig/couch.rb', line 50

def name

  path
end

#nuke_design_documents ⇒ Object

A development method. Removes all the design documents in this couch database.

Used in tests setup or teardown, when views are subject to frequent changes (rufus-doric and co).



360
361
362
363
364
365
366
367
# File 'lib/rufus/jig/couch.rb', line 360

def nuke_design_documents

  docs = get('_all_docs')['rows']

  views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) }

  views.each { |v| delete(v['id'], v['value']['rev']) }
end

#on_change(opts = {}, &block) ⇒ Object

Watches the database for changes.

db.on_change do |doc_id, deleted|
puts "doc #{doc_id} has been #{deleted ? 'deleted' : 'changed'}"
end

db.on_change do |doc_id, deleted, doc|
puts "doc #{doc_id} has been #{deleted ? 'deleted' : 'changed'}"
p doc
end

This is a blocking method. One might want to wrap it inside of a Thread.

Note : doc inclusion (third parameter to the block) only works with CouchDB >= 0.11.



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/rufus/jig/couch.rb', line 297

def on_change(opts={}, &block)

  query = {
    'feed' => 'continuous',
    'heartbeat' => opts[:heartbeat] || 20_000 }
    #'since' => 0 } # that's already the default
  query['include_docs'] = true if block.arity > 2
  query = query.map { |k, v| "#{k}=#{v}" }.join('&')

  socket = TCPSocket.open(@http.host, @http.port)

  auth = @http.options[:basic_auth]

  if auth
    auth = Base64.encode64(auth.join(':')).strip
    auth = "Authorization: Basic #{auth}\r\n"
  else
    auth = ''
  end

  socket.print("GET /#{path}/_changes?#{query} HTTP/1.1\r\n")
  socket.print("User-Agent: rufus-jig #{Rufus::Jig::VERSION}\r\n")
  #socket.print("Accept: application/json;charset=UTF-8\r\n")
  socket.print(auth)
  socket.print("\r\n")

  # consider reply

  answer = socket.gets.strip
  status = answer.match(/^HTTP\/.+ (\d{3}) /)[1].to_i

  raise Rufus::Jig::HttpError.new(status, answer) if status != 200

  # discard headers

  loop do
    data = socket.gets
    break if data.nil? || data == "\r\n"
  end

  # the on_change loop

  loop do
    data = socket.gets
    break if data.nil?
    data = (Rufus::Json.decode(data) rescue nil)
    next unless data.is_a?(Hash)
    args = [ data['id'], (data['deleted'] == true) ]
    args << data['doc'] if block.arity > 2
    block.call(*args)
  end

  on_change(opts, &block) if opts[:reconnect]
end

#post(path, doc, opts = {}) ⇒ Object



192
193
194
195
# File 'lib/rufus/jig/couch.rb', line 192

def post(path, doc, opts={})

  @http.post(adjust(path), doc, opts.merge(:content_type => :json))
end

#put(doc_or_path, opts = {}) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rufus/jig/couch.rb', line 60

def put(doc_or_path, opts={})

  path, payload = if doc_or_path.is_a?(String)
    [ doc_or_path, '' ]
  else
    [ doc_or_path['_id'], doc_or_path ]
  end

  pa = adjust(path)

  #if @opts[:re_put_ok] == false && payload['_rev']
  #  rr = delete(path, payload['_rev'])
  #  return rr unless rr.nil?
  #end

  r = @http.put(pa, payload, :content_type => :json, :cache => false)

  return @http.get(pa) || true if r == true
    #
    # conflict : returns the current version of the doc
    # (or true if there is no document (probably 404 for the database))

  if opts[:update_rev] && doc_or_path.is_a?(Hash)
    doc_or_path['_rev'] = r['rev']
  end

  nil
end

#query(path, opts = {}) ⇒ Object

Queries a view.

res = couch.query('_design/my_test/_view/my_view')
#
#   [ {"id"=>"c3", "key"=>"capuccino", "value"=>nil},
#     {"id"=>"c0", "key"=>"espresso", "value"=>nil},
#     {"id"=>"c2", "key"=>"macchiato", "value"=>nil},
#     {"id"=>"c4", "key"=>"macchiato", "value"=>nil},
#     {"id"=>"c1", "key"=>"ristretto", "value"=>nil} ]

# or simply :

res = couch.query('my_test:my_view')

Accepts the usual couch parameters : limit, skip, descending, keys, startkey, endkey, ...



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/rufus/jig/couch.rb', line 386

def query(path, opts={})

  opts = opts.dup
    # don't touch the original

  raw = opts.delete(:raw)

  path = if DESIGN_PATH_REGEX.match(path)
    path
  else
    doc_id, view = path.split(':')
    path = "_design/#{doc_id}/_view/#{view}"
  end

  path = adjust(path)

  adjust_params(opts)

  keys = opts.delete(:keys)

  res = if keys
    opts[:cache] = :with_body if opts[:cache].nil?
    @http.post(path, { 'keys' => keys }, opts)
  else
    @http.get(path, opts)
  end

  return nil if res == true
    # POST and the view doesn't exist

  return res if raw

  res.nil? ? res : res['rows']
end

#query_for_docs(path, opts = {}) ⇒ Object

A shortcut for

query(path, :include_docs => true).collect { |row| row['doc'] }


425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/rufus/jig/couch.rb', line 425

def query_for_docs(path, opts={})

  res = query(path, opts.merge(:include_docs => true))

  if res.nil?
    nil
  elsif opts[:raw]
    res
  else
    res.collect { |row| row['doc'] }.uniq
  end
end