lib/dolly/collection.rb in dolly-1.1.7 vs lib/dolly/collection.rb in dolly-3.0.0

- old
+ new

@@ -1,88 +1,45 @@ module Dolly - class Collection < DelegateClass(Set) - attr_accessor :rows - attr_writer :json, :docs_class + class Collection < DelegateClass(Array) + attr_reader :info - def initialize str, docs_class - @docs_class = docs_class - @json = str - initial = [] - super(initial) - load + def initialize(rows: [], **info) + @info = info + #TODO: We should raise an exception if one of the + # requested documents is missing + super rows.map(&collect_docs).compact end - def last - to_a.last + def first_or_all(forced_first = false) + return self if forced_first + single? ? first : self end - def update_properties! properties ={} - properties.each do |key, value| - - regex = %r{ - \"#{key}\": # find key definition in json string - ( # start value group - \"[^\"]*\" # find anything (even empty) between \" and \" - | # logical OR - null #literal null value - ) # end value group - }x - - raise Dolly::MissingPropertyError unless json.match regex - json.gsub! regex, "\"#{key}\":\"#{value}\"" - end - - BulkDocument.new(Dolly::Document.database, to_a).save - clear - load - self + def single? + size <= 1 end - def each &block - load if empty? - super &block - #TODO: returning nil to avoid extra time serializing set. - nil - end + private - def rows= ary - ary.each do |r| - next unless r['doc'] - properties = r['doc'] - id = properties.delete '_id' - rev = properties.delete '_rev' if properties['_rev'] - document = (docs_class || doc_class(id)).new properties - document.doc = properties.merge({'_id' => id, '_rev' => rev}) - self << document + def collect_docs + lambda do |row| + next unless collectable_row?(row) + klass = Object.const_get doc_type(row[:id]) + klass.from_doc(row[:doc]) end end - def load - parsed = JSON::parse json - self.rows = parsed['rows'] + def doc_type(key) + key.match(%r{^([^/]+)/})[1].split('_').collect(&:capitalize).join end - def to_json options = {} - load if empty? - map{|r| r.doc }.to_json(options) + def collectable_row?(row) + !deleted_doc?(row) && row[:error].nil? end - private - def docs_class - @docs_class + def deleted_doc?(row) + value = row&.fetch(:value, {}) + return false unless value.is_a? Hash + value.fetch(:deleted, false) end - - def doc_class id - # TODO: We need to improve and document the way we return - # multiple types when querying from a class, as it might - # be confusing. We *could* also get dolly to parse the result - # before sending it back to the client. - doc_class = id[/^[a-z_]+/].camelize.constantize - docs_class == doc_class ? docs_class : doc_class - end - - def json - @json - end - end end