Created
April 5, 2011 05:39
-
-
Save lyleunderwood/903089 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
include DataImporting::Importable | |
include Amf::Serialization | |
field :number | |
field :name | |
field :gender | |
field :region | |
field :features | |
field :tags | |
field :position, :type => Integer | |
embeds_one :catalog | |
embeds_many :variations, :class_name => 'NestedVariation', :autosave => true | |
index :name | |
index :number | |
scope :search_with, lambda {|query| query_search(query)} | |
# search across all products by various parameters | |
def self.query_search(query) | |
crit = all | |
return crit if query.blank? | |
# build up our crit | |
crit = crit.merge(keyword_search(query[:keyword])) unless query[:keyword].blank? | |
crit = crit.merge(catalog_search(query[:catalog])) unless query[:catalog].blank? | |
crit = crit.merge(color_search(query[:color])) unless query[:color].blank? | |
crit = crit.merge(sort_search(query[:sort])) unless query[:sort].blank? | |
crit = crit.merge(tag_search(query[:tags])) unless query[:tags].blank? | |
crit | |
end | |
def self.keyword_search(keyword) | |
keyword_regex = Regexp.new(keyword, true) | |
# not calling criteria makes this conflict with the or keyword | |
criteria.or( | |
{:number => keyword}, | |
{:name => keyword_regex}, | |
{"variations.base_color" => keyword_regex} | |
) | |
end | |
def self.catalog_search(catalog) | |
where("catalog.name" => catalog) | |
end | |
def self.color_search(color) | |
where("variations.base_color" => color) | |
end | |
def self.tag_search(tags) | |
crit = criteria | |
tags.each_pair { |k,v| crit = crit.and("tags.#{k}" => v) } | |
crit | |
end | |
def self.sort_search(sort) | |
# TODO: fill the rest of this in | |
types = {'workbook' => :_id, 'name' => :name, 'price' => :number} | |
directions = {'asc' => :asc, 'desc' => :desc} | |
type = types[sort[:type]] || :_id | |
direction = directions[sort[:direction]] || :desc | |
order_by([[type, direction]]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment