lib/ripple/document/finders.rb in ripple-0.6.1 vs lib/ripple/document/finders.rb in ripple-0.7.0
- old
+ new
@@ -12,10 +12,31 @@
# See the License for the specific language governing permissions and
# limitations under the License.
require 'ripple'
module Ripple
+
+ # Raised by <tt>find!</tt> when a document cannot be found with the given key.
+ # begin
+ # Example.find!('badkey')
+ # rescue Ripple::DocumentNotFound
+ # puts 'No Document here!'
+ # end
+ class DocumentNotFound < StandardError
+ include Translation
+ def initialize(keys, found)
+ if keys.empty?
+ super(t("document_not_found.no_key"))
+ elsif keys.one?
+ super(t("document_not_found.one_key", :key => keys.first))
+ else
+ missing = keys - found.compact.map(&:key)
+ super(t("document_not_found.many_keys", :keys => missing.join(', ')))
+ end
+ end
+ end
+
module Document
module Finders
extend ActiveSupport::Concern
module ClassMethods
@@ -33,14 +54,37 @@
# Find a list of documents.
# @param [Array<String>] keylist an array of keys to find
# @return [Array<Document>] a list of found documents, including nil for missing documents
def find(*args)
args.flatten!
- return [] if args.length == 0
- return find_one(args.first) if args.length == 1
+ return nil if args.empty?
+ return find_one(args.first) if args.one?
args.map {|key| find_one(key) }
end
+
+ # Retrieve single or multiple documents from Riak
+ # but raise Ripple::DocumentNotFound if a key can
+ # not be found in the bucket.
+ def find!(*args)
+ found = find(*args)
+ raise DocumentNotFound.new(args, found) if !found || Array(found).include?(nil)
+ found
+ end
+
+ # Find the first object using the first key in the
+ # bucket's keys using find. You should not expect to
+ # actually get the first object you added to the bucket.
+ # This is just a convenience method.
+ def first
+ find(bucket.keys.first)
+ end
+
+ # Find the first object using the first key in the
+ # bucket's keys using find!
+ def first!
+ find!(bucket.keys.first)
+ end
# Find all documents in the Document's bucket and return them.
# @overload all()
# Get all documents and return them in an array.
# @return [Array<Document>] all found documents in the bucket
@@ -72,10 +116,13 @@
raise fr
end
def instantiate(robject)
klass = robject.data['_type'].constantize rescue self
- klass.new(robject.data.merge('key' => robject.key)).tap do |doc|
+ data = {'key' => robject.key}
+ data.reverse_merge!(robject.data) rescue data
+ klass.new(data).tap do |doc|
+ doc.key = data['key']
doc.instance_variable_set(:@new, false)
doc.instance_variable_set(:@robject, robject)
end
end
end