Commit cb7b07bb

mo khan <mo@mokhan.ca>
2014-10-19 01:28:45
add search by name and description.
1 parent 6a07f43
Changed files (4)
app
models
services
spec
app/models/creation/repository.rb
@@ -2,6 +2,7 @@ class Creation
   include Filterable
   scope :tagged, ->(tag) { tagged_with([tag]).where('photos_count > 0') }
   scope :published, ->() { unscoped.distinct.includes(:user, :photos).joins(:photos).where('photos.image_processing' => nil) }
+  scope :search, ->(query) { where(["upper(creations.name) like :query OR upper(creations.story) like :query", { query: "%#{query.upcase}%" }]) }
 
   class Repository < SimpleDelegator
     def initialize(connection = Creation)
@@ -14,7 +15,7 @@ class Creation
     end
 
     def search(query)
-      connection.includes(:user, :photos).where(["upper(name) like :query OR upper(story) like :query", { query: "%#{query.upcase}%" }])
+      connection.includes(:user, :photos).search(query)
     end
 
     private
app/services/application/all_cakes_query.rb
@@ -13,6 +13,7 @@ class AllCakesQuery
     [
       ->(cakes) { cakes.published },
       ->(cakes) { params[:category].blank? ? cakes.all : cakes.where(category: Category.find_by(slug: params[:category].downcase)) },
+      ->(cakes) { params[:q].blank? ? cakes.all : cakes.search(params[:q]) },
       ->(cakes) { cakes.order(created_at: sort(params)) },
     ]
   end
spec/services/application/all_cakes_query_spec.rb
@@ -37,5 +37,11 @@ describe AllCakesQuery do
       expect(cakes).to include(cake)
       expect(cakes).to_not include(cookie)
     end
+
+    it 'returns all cakes that match the search query' do
+      cakes = subject.fetch(q: cake.name[0..2])
+      expect(cakes).to include(cake)
+      expect(cakes).to_not include(cookie)
+    end
   end
 end
spec/factories.rb
@@ -16,7 +16,7 @@ FactoryGirl.define do
 
   factory :cake, class: Creation do
     name { Faker::Name.name }
-    story 'whats the story morning glory?'
+    story { Faker::HipsterIpsum.words(50).join(' ') }
     association :user
     association :category
   end