Sha256: 8d2aaa038446ef514c03fc5698473f7fdcad8b789d1b7012373c32ca4ed6da64

Contents?: true

Size: 1.71 KB

Versions: 11

Compression:

Stored size: 1.71 KB

Contents

module CouchPotato
  module View
    # A view to return model instances by searching its properties.
    # If you pass reduce => true will count instead
    #
    # example:
    #   view :my_view, :key => :name
    # 
    # in addition you can pass in conditions as a javascript string
    #   view :my_view_only_completed, :key => :name, :conditions => 'doc.completed = true'
    class ModelViewSpec < BaseViewSpec
      
      def view_parameters
        _super = super
        if _super[:reduce]
          _super
        else
          {:include_docs => true, :reduce => false}.merge(_super)
        end
      end
      
      def map_function
        map_body do
          "emit(#{formatted_key(key)}, 1);"
        end
      end
      
      def reduce_function
        "function(key, values) {
          return sum(values);
        }"
      end
      
      def process_results(results)
        if count?
          results['rows'].first.try(:[], 'value') || 0
        else
          results['rows'].map { |row| row['doc'] }
        end
      end
      
      private
      
      def map_body(&block)
        "function(doc) {
           if(doc.#{JSON.create_id} && doc.#{JSON.create_id} == '#{@klass.name}'#{conditions_js}) {
             " + yield + "
           }
         }"
        
      end
      
      def conditions_js
        " && (#{options[:conditions]})" if options[:conditions]
      end
      
      def count?
        view_parameters[:reduce]
      end
      
      def key
        options[:key]
      end
      
      def formatted_key(key)
        if key.is_a? Array
          '[' + key.map{|attribute| formatted_key(attribute)}.join(', ') + ']'
        else
          "doc['#{key}']"
        end
      end
      
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
couch_potato-0.3.0 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.32 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.31 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.30 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.29 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.28 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.27 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.26 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.25 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.24 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.23 lib/couch_potato/view/model_view_spec.rb