Class: RelaxDB::SortedByView

Inherits:
Object
  • Object
show all
Defined in:
lib/relaxdb/sorted_by_view.rb

Overview

 Represents a CouchDB view, which is implicitly sorted by key The view name is determined by sort attributes

Instance Method Summary collapse

Constructor Details

#initialize(class_name, *atts) ⇒ SortedByView

Returns a new instance of SortedByView.



7
8
9
10
# File 'lib/relaxdb/sorted_by_view.rb', line 7

def initialize(class_name, *atts)
  @class_name = class_name
  @atts = atts
end

Instance Method Details

#map_functionObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/relaxdb/sorted_by_view.rb', line 12

def map_function
  key = @atts.map { |a| "doc.#{a}" }.join(", ")
  key = @atts.size > 1 ? key.sub(/^/, "[").sub(/$/, "]") : key

  <<-QUERY
  function(doc) {
    if(doc.class == "#{@class_name}") {
      emit(#{key}, doc);
    }
  }
  QUERY
end

#query(query) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/relaxdb/sorted_by_view.rb', line 41

def query(query)
  # If a view contains both a map and reduce function, CouchDB will by default return 
  # the result of the reduce function when queried. 
  # This class automatically creates both map and reduce functions so it can be used by the paginator.
  # In normal usage, this class will be used with map functions, hence reduce is explicitly set 
  # to false if it hasn't already been set.
  query.reduce(false) if query.reduce.nil?
  
  method = query.keys ? :post : :get
  
  begin
    resp = RelaxDB.db.send(method, query.view_path, query.keys)
  rescue => e
    design_doc = DesignDocument.get(@class_name) 
    design_doc.add_map_view(view_name, map_function).add_reduce_view(view_name, reduce_function).save
    resp = RelaxDB.db.send(method, query.view_path, query.keys)        
  end

  data = JSON.parse(resp.body)
  ViewResult.new(data)            
end

#reduce_functionObject



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/relaxdb/sorted_by_view.rb', line 25

def reduce_function
  <<-QUERY
  function(keys, values, rereduce) {
    if (rereduce) {
      return sum(values);
    } else {
      return values.length;
    }
  }
  QUERY
end

#view_nameObject



37
38
39
# File 'lib/relaxdb/sorted_by_view.rb', line 37

def view_name
  "all_sorted_by_" << @atts.join("_and_")
end