lib/scoped_search/definition.rb in scoped_search-2.0.1 vs lib/scoped_search/definition.rb in scoped_search-2.2.0

- old
+ new

@@ -72,10 +72,12 @@ # Initializes a Field instance given the definition passed to the # scoped_search call on the ActiveRecord-based model class. def initialize(definition, options = {}) @definition = definition + @definition.profile = options[:profile] if options[:profile] + case options when Symbol, String @field = field.to_sym when Hash @field = options.delete(:on) @@ -94,23 +96,37 @@ definition.fields[options[:alias]] ||= self if options[:alias] options[:aliases].each { |al| definition.fields[al] ||= self } if options[:aliases] end end - attr_reader :klass, :fields, :unique_fields + attr_reader :klass # Initializes a ScopedSearch definition instance. # This method will also setup a database adapter and create the :search_for # named scope if it does not yet exist. def initialize(klass) - @klass = klass - @fields = {} - @unique_fields = [] + @klass = klass + @fields = {} + @unique_fields = [] + @profile_fields = {:default => {}} + @profile_unique_fields = {:default => []} register_named_scope! unless klass.respond_to?(:search_for) end + + attr_accessor :profile + + def fields + @profile ||= :default + @profile_fields[@profile] ||= {} + end + def unique_fields + @profile ||= :default + @profile_unique_fields[@profile] ||= [] + end + NUMERICAL_REGXP = /^\-?\d+(\.\d+)?$/ # Returns a list of appropriate fields to search in given a search keyword and operator. def default_fields_for(value, operator = nil) @@ -137,9 +153,26 @@ protected # Registers the search_for named scope within the class that is used for searching. def register_named_scope! # :nodoc - @klass.named_scope(:search_for, lambda { |*args| ScopedSearch::QueryBuilder.build_query(args[1] || self, args[0]) }) + if @klass.ancestors.include?(ActiveRecord::Base) + case ActiveRecord::VERSION::MAJOR + when 2 + @klass.named_scope(:search_for, lambda { |*args| ScopedSearch::QueryBuilder.build_query(self, args[0], args[1]) }) + when 3 + @klass.scope(:search_for, lambda { |*args| + find_options = ScopedSearch::QueryBuilder.build_query(self, args[0], args[1]) + search_scope = @klass.scoped + search_scope = search_scope.where(find_options[:conditions]) if find_options[:conditions] + search_scope = search_scope.includes(find_options[:include]) if find_options[:include] + search_scope + }) + else + raise "This ActiveRecord version is currently not supported!" + end + else + raise "Currently, only ActiveRecord 2.1 or higher is supported!" + end end end end