Class: Couchbase::View

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

Instance Method Summary collapse

Constructor Details

#initialize(connection, endpoint, params = {}) ⇒ View

Set up view endpoint and optional params

stores all info about how to make requests to Couchbase views.

Couchbase::View#each

Parameters:

  • connection (Couchbase::Bucket)

    Connection object which

  • endpoint (String)

    Full CouchDB view URI.

  • params (Hash) (defaults to: {})

    Optional parameter which will be passed to



34
35
36
37
38
# File 'lib/couchbase/view.rb', line 34

def initialize(connection, endpoint, params = {})
  @connection = connection
  @endpoint = endpoint
  @params = params
end

Instance Method Details

#each(params = {}) ⇒ Object

Yields each document that was fetched by view. It doesn’t instantiate all the results because of streaming JSON parser. Returns Enumerator unless block given.

:startkey, :startkey_docid, :descending.

Examples:

Use each method with block


view.each do |doc|
  # do something with doc
end

Use Enumerator version


enum = view.each  # request hasn't issued yet
enum.map{|doc| doc.title.upcase}

Pass options during view initialization


endpoint = "http://localhost:5984/default/_design/blog/_view/recent"
view = View.new(conn, endpoint, :descending => true)
view.each do |document|
  # do something with document
end

Parameters:

  • params (Hash) (defaults to: {})

    Params for Couchdb query. Some useful are:



66
67
68
69
# File 'lib/couchbase/view.rb', line 66

def each(params = {})
  return enum_for(:each, params) unless block_given?
  fetch(params) {|doc| yield(doc)}
end

#fetch(params = {}) {|document| ... } ⇒ Array

Performs query to CouchDB view. This method will stream results if block given or return complete result set otherwise. In latter case it defines method total_entries returning total_rows entry from CouchDB result object.

Parameters:

Yield Parameters:

Returns:

  • (Array)

    with documents. There will be total_entries method defined on this array if it’s possible.

Raises:

  • (Couchbase::ViewError)

    when on_error callback is nil and error object found in the result stream.



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/couchbase/view.rb', line 128

def fetch(params = {})
  curl = @connection.curl_easy(@endpoint, :params => @params.merge(params))
  if block_given?
    iter = YAJI::Parser.new(curl).each(["rows/", "errors/"], :with_path => true)
    begin
      loop do
        path, obj = iter.next
        if path == "errors/"
          from, reason = obj["from"], obj["reason"]
          if @on_error
            @on_error.call(from, reason)
          else
            raise ViewError.new(from, reason)
          end
        else
          yield Document.new(self, obj)
        end
      end
    rescue StopIteration
    end
  else
    iter = YAJI::Parser.new(curl).each(["total_rows", "rows/", "errors/"], :with_path => true)
    docs = []
    begin
      path, obj = iter.next
      if path == "total_rows"
        # if total_rows key present, save it and take next object
        total_rows = obj
        path, obj = iter.next
      end
      loop do
        if path == "errors/"
          from, reason = obj["from"], obj["reason"]
          if @on_error
            @on_error.call(from, reason)
          else
            raise ViewError.new(from, reason)
          end
        else
          docs << Document.new(self, obj)
        end
        path, obj = iter.next
      end
    rescue StopIteration
    end
    docs.instance_eval("def total_entries; #{total_rows}; end")
    return docs
  end
end

#inspectObject



178
179
180
# File 'lib/couchbase/view.rb', line 178

def inspect
  %(#<#{self.class.name}:#{self.object_id} @endpoint=#{@endpoint.inspect} @params=#{@params.inspect}>)
end

#on_error {|from, reason| ... } ⇒ Object

Registers callback function for handling error objects in view results stream.

Examples:

Using #on_error to log all errors in view result


# JSON-encoded view result
#
# {
#   "total_rows": 0,
#   "rows": [ ],
#   "errors": [
#     {
#       "from": "127.0.0.1:5984",
#       "reason": "Design document `_design/testfoobar` missing in database `test_db_b`."
#     },
#     {
#       "from": "http:// localhost:5984/_view_merge/",
#       "reason": "Design document `_design/testfoobar` missing in database `test_db_c`."
#     }
#   ]
# }

view.on_error do |from, reason|
  logger.warn("#{view.inspect} received the error '#{reason}' from #{from}")
end
docs = view.fetch

More concise example to just count errors


errcount = 0
view.on_error{|f,r| errcount += 1}.fetch

Yield Parameters:

  • from (String)

    Location of the node where error occured

  • reason (String)

    The reason message describing what happened.



107
108
109
110
# File 'lib/couchbase/view.rb', line 107

def on_error(&callback)
  @on_error = callback
  self  # enable call chains
end