Sha256: 9a7adad2826e3e89275e180186f59f08ce3a2e007f7b62f4a5ed4151114ff23b

Contents?: true

Size: 1.36 KB

Versions: 12

Compression:

Stored size: 1.36 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
    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
        "function(doc) {
           if(doc.ruby_class && doc.ruby_class == '#{@klass.name}') {
             emit(#{formatted_key(key)}, null);
           }
         }"
      end
      
      def reduce_function
        "function(key, values) {
          return values.length;
        }"
      end
      
      def process_results(results)
        if count?
          results['rows'].first.try(:[], 'value') || 0
        else
          results['rows'].map do |row|
            klass.json_create row['doc']
          end
        end
      end
      
      private
      
      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

12 entries across 12 versions & 4 rubygems

Version Path
andrewtimberlake-couch_potato-0.2.8.1 lib/couch_potato/view/model_view_spec.rb
andrewtimberlake-couch_potato-0.2.8.2 lib/couch_potato/view/model_view_spec.rb
andrewtimberlake-couch_potato-0.2.8.3 lib/couch_potato/view/model_view_spec.rb
andrewtimberlake-couch_potato-0.2.8.4 lib/couch_potato/view/model_view_spec.rb
langalex-couch_potato-0.2.11 lib/couch_potato/view/model_view_spec.rb
langalex-couch_potato-0.2.12 lib/couch_potato/view/model_view_spec.rb
langalex-couch_potato-0.2.6 lib/couch_potato/view/model_view_spec.rb
langalex-couch_potato-0.2.7 lib/couch_potato/view/model_view_spec.rb
langalex-couch_potato-0.2.8 lib/couch_potato/view/model_view_spec.rb
langalex-couch_potato-0.2.9 lib/couch_potato/view/model_view_spec.rb
thefool808-couch_potato-0.2.7 lib/couch_potato/view/model_view_spec.rb
couch_potato-0.2.12 lib/couch_potato/view/model_view_spec.rb