aq1018-searchlogic 2.4.15

Sign up to get free protection for your applications and to get access to all the features.
Files changed (34) hide show
  1. data/.gitignore +6 -0
  2. data/LICENSE +20 -0
  3. data/README.rdoc +308 -0
  4. data/Rakefile +35 -0
  5. data/VERSION.yml +5 -0
  6. data/init.rb +1 -0
  7. data/lib/searchlogic/active_record/association_proxy_overrides.rb +53 -0
  8. data/lib/searchlogic/active_record/consistency.rb +49 -0
  9. data/lib/searchlogic/active_record/named_scope_tools.rb +101 -0
  10. data/lib/searchlogic/core_ext/object.rb +43 -0
  11. data/lib/searchlogic/core_ext/proc.rb +17 -0
  12. data/lib/searchlogic/named_scopes/alias_scope.rb +67 -0
  13. data/lib/searchlogic/named_scopes/association_conditions.rb +131 -0
  14. data/lib/searchlogic/named_scopes/association_ordering.rb +44 -0
  15. data/lib/searchlogic/named_scopes/conditions.rb +228 -0
  16. data/lib/searchlogic/named_scopes/or_conditions.rb +141 -0
  17. data/lib/searchlogic/named_scopes/ordering.rb +48 -0
  18. data/lib/searchlogic/rails_helpers.rb +76 -0
  19. data/lib/searchlogic/search.rb +231 -0
  20. data/lib/searchlogic.rb +47 -0
  21. data/rails/init.rb +1 -0
  22. data/spec/active_record/association_proxy_override_spec.rb +23 -0
  23. data/spec/active_record/consistency_spec.rb +28 -0
  24. data/spec/core_ext/object_spec.rb +9 -0
  25. data/spec/core_ext/proc_spec.rb +8 -0
  26. data/spec/named_scopes/alias_scope_spec.rb +19 -0
  27. data/spec/named_scopes/association_conditions_spec.rb +188 -0
  28. data/spec/named_scopes/association_ordering_spec.rb +27 -0
  29. data/spec/named_scopes/conditions_spec.rb +319 -0
  30. data/spec/named_scopes/or_conditions_spec.rb +66 -0
  31. data/spec/named_scopes/ordering_spec.rb +34 -0
  32. data/spec/search_spec.rb +423 -0
  33. data/spec/spec_helper.rb +132 -0
  34. metadata +119 -0
@@ -0,0 +1,67 @@
1
+ module Searchlogic
2
+ module NamedScopes
3
+ # Adds the ability to create alias scopes that allow you to alias a named
4
+ # scope or create a named scope procedure. See the alias_scope method for a more
5
+ # detailed explanation.
6
+ module AliasScope
7
+ # In some instances you might create a class method that essentially aliases a named scope
8
+ # or represents a named scope procedure. Ex:
9
+ #
10
+ # class User
11
+ # def teenager
12
+ # age_gte(13).age_lte(19)
13
+ # end
14
+ # end
15
+ #
16
+ # This is obviously a very basic example, but notice how we are utilizing already existing named
17
+ # scopes so that we do not have to repeat ourself. This method makes a lot more sense when you are
18
+ # dealing with complicated named scope.
19
+ #
20
+ # There is a problem though. What if you want to use this in your controller's via the 'search' method:
21
+ #
22
+ # User.search(:teenager => true)
23
+ #
24
+ # You would expect that to work, but how does Searchlogic::Search tell the difference between your
25
+ # 'teenager' method and the 'destroy_all' method. It can't, there is no way to tell unless we actually
26
+ # call the method, which we obviously can not do.
27
+ #
28
+ # The being said, we need a way to tell searchlogic that this is method is safe. Here's how you do that:
29
+ #
30
+ # User.alias_scope :teenager, lambda { age_gte(13).age_lte(19) }
31
+ #
32
+ # This feels better, it feels like our other scopes, and it provides a way to tell Searchlogic that this
33
+ # is a safe method.
34
+ def alias_scope(name, options = nil)
35
+ alias_scopes[name.to_sym] = options
36
+ (class << self; self end).instance_eval do
37
+ define_method name do |*args|
38
+ case options
39
+ when Symbol
40
+ send(options)
41
+ else
42
+ options.call(*args)
43
+ end
44
+ end
45
+ end
46
+ end
47
+ alias_method :scope_procedure, :alias_scope
48
+
49
+ def alias_scopes # :nodoc:
50
+ @alias_scopes ||= {}
51
+ end
52
+
53
+ def alias_scope?(name) # :nodoc:
54
+ return false if name.blank?
55
+ alias_scopes.key?(name.to_sym)
56
+ end
57
+
58
+ def condition?(name) # :nodoc:
59
+ super || alias_scope?(name)
60
+ end
61
+
62
+ def named_scope_options(name) # :nodoc:
63
+ super || alias_scopes[name.to_sym]
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,131 @@
1
+ module Searchlogic
2
+ module NamedScopes
3
+ # Handles dynamically creating named scopes for associations. See the README for a detailed explanation.
4
+ module AssociationConditions
5
+ def condition?(name) # :nodoc:
6
+ super || association_condition?(name)
7
+ end
8
+
9
+ private
10
+ def association_condition?(name)
11
+ !association_condition_details(name).nil? unless name.to_s.downcase.match("_or_")
12
+ end
13
+
14
+ def method_missing(name, *args, &block)
15
+ if !local_condition?(name) && details = association_condition_details(name)
16
+ create_association_condition(details[:association], details[:condition], args, details[:poly_class])
17
+ send(name, *args)
18
+ else
19
+ super
20
+ end
21
+ end
22
+
23
+ def association_condition_details(name, last_condition = nil)
24
+ non_poly_assocs = reflect_on_all_associations.reject { |assoc| assoc.options[:polymorphic] }.sort { |a, b| b.name.to_s.size <=> a.name.to_s.size }
25
+ poly_assocs = reflect_on_all_associations.reject { |assoc| !assoc.options[:polymorphic] }.sort { |a, b| b.name.to_s.size <=> a.name.to_s.size }
26
+ return nil if non_poly_assocs.empty? && poly_assocs.empty?
27
+
28
+ name_with_condition = [name, last_condition].compact.join('_')
29
+
30
+ association_name = nil
31
+ poly_type = nil
32
+ condition = nil
33
+
34
+ if name_with_condition.to_s =~ /^(#{non_poly_assocs.collect(&:name).join("|")})_(\w+)$/
35
+ association_name = $1
36
+ condition = $2
37
+ elsif name_with_condition.to_s =~ /^(#{poly_assocs.collect(&:name).join("|")})_(\w+?)_type_(\w+)$/
38
+ association_name = $1
39
+ poly_type = $2
40
+ condition = $3
41
+ end
42
+
43
+ if association_name && condition
44
+ association = reflect_on_association(association_name.to_sym)
45
+ klass = poly_type ? poly_type.camelcase.constantize : association.klass
46
+ if klass.condition?(condition)
47
+ {:association => association, :poly_class => poly_type && klass, :condition => condition}
48
+ else
49
+ nil
50
+ end
51
+ end
52
+ end
53
+
54
+ def create_association_condition(association, condition_name, args, poly_class = nil)
55
+ name = [association.name, poly_class && "#{poly_class.name.underscore}_type", condition_name].compact.join("_")
56
+ named_scope(name, association_condition_options(association, condition_name, args, poly_class))
57
+ end
58
+
59
+ def association_condition_options(association, association_condition, args, poly_class = nil)
60
+ klass = poly_class ? poly_class : association.klass
61
+ scope = klass.send(association_condition, *args)
62
+ scope_options = klass.named_scope_options(association_condition)
63
+ arity = klass.named_scope_arity(association_condition)
64
+
65
+ if !arity || arity == 0
66
+ # The underlying condition doesn't require any parameters, so let's just create a simple
67
+ # named scope that is based on a hash.
68
+ options = {}
69
+ in_searchlogic_delegation { options = scope.scope(:find) }
70
+ prepare_named_scope_options(options, association, poly_class)
71
+ options
72
+ else
73
+ proc_args = arity_args(arity)
74
+ arg_type = (scope_options.respond_to?(:searchlogic_options) && scope_options.searchlogic_options[:type]) || :string
75
+
76
+ eval <<-"end_eval"
77
+ searchlogic_lambda(:#{arg_type}) { |#{proc_args.join(",")}|
78
+ options = {}
79
+
80
+ in_searchlogic_delegation do
81
+ scope = klass.send(association_condition, #{proc_args.join(",")})
82
+ options = scope.scope(:find) if scope
83
+ end
84
+
85
+
86
+ prepare_named_scope_options(options, association, poly_class)
87
+ options
88
+ }
89
+ end_eval
90
+ end
91
+ end
92
+
93
+ # Used to match the new scopes parameters to the underlying scope. This way we can disguise the
94
+ # new scope as best as possible instead of taking the easy way out and using *args.
95
+ def arity_args(arity)
96
+ args = []
97
+ if arity > 0
98
+ arity.times { |i| args << "arg#{i}" }
99
+ else
100
+ positive_arity = arity * -1
101
+ positive_arity.times do |i|
102
+ if i == (positive_arity - 1)
103
+ args << "*arg#{i}"
104
+ else
105
+ args << "arg#{i}"
106
+ end
107
+ end
108
+ end
109
+ args
110
+ end
111
+
112
+ def prepare_named_scope_options(options, association, poly_class = nil)
113
+ options.delete(:readonly) # AR likes to set :readonly to true when using the :joins option, we don't want that
114
+
115
+ klass = poly_class || association.klass
116
+ # sanitize the conditions locally so we get the right table name, otherwise the conditions will be evaluated on the original model
117
+ options[:conditions] = klass.sanitize_sql_for_conditions(options[:conditions]) if options[:conditions].is_a?(Hash)
118
+
119
+ poly_join = poly_class && inner_polymorphic_join(poly_class.name.underscore, :as => association.name)
120
+
121
+ if options[:joins].is_a?(String) || array_of_strings?(options[:joins])
122
+ options[:joins] = [poly_class ? poly_join : inner_joins(association.name), options[:joins]].flatten
123
+ elsif poly_class
124
+ options[:joins] = options[:joins].blank? ? poly_join : ([poly_join] + klass.inner_joins(options[:joins]))
125
+ else
126
+ options[:joins] = options[:joins].blank? ? association.name : {association.name => options[:joins]}
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,44 @@
1
+ module Searchlogic
2
+ module NamedScopes
3
+ # Handles dynamically creating order named scopes for associations:
4
+ #
5
+ # User.has_many :orders
6
+ # Order.has_many :line_items
7
+ # LineItem
8
+ #
9
+ # User.ascend_by_orders_line_items_id
10
+ #
11
+ # See the README for a more detailed explanation.
12
+ module AssociationOrdering
13
+ def condition?(name) # :nodoc:
14
+ super || association_ordering_condition?(name)
15
+ end
16
+
17
+ private
18
+ def association_ordering_condition?(name)
19
+ !association_ordering_condition_details(name).nil?
20
+ end
21
+
22
+ def method_missing(name, *args, &block)
23
+ if details = association_ordering_condition_details(name)
24
+ create_association_ordering_condition(details[:association], details[:order_as], details[:condition], args)
25
+ send(name, *args)
26
+ else
27
+ super
28
+ end
29
+ end
30
+
31
+ def association_ordering_condition_details(name)
32
+ associations = reflect_on_all_associations
33
+ association_names = associations.collect { |assoc| assoc.name }
34
+ if name.to_s =~ /^(ascend|descend)_by_(#{association_names.join("|")})_(\w+)$/
35
+ {:order_as => $1, :association => associations.find { |a| a.name == $2.to_sym }, :condition => $3}
36
+ end
37
+ end
38
+
39
+ def create_association_ordering_condition(association, order_as, condition, args)
40
+ named_scope("#{order_as}_by_#{association.name}_#{condition}", association_condition_options(association, "#{order_as}_by_#{condition}", args))
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,228 @@
1
+ module Searchlogic
2
+ module NamedScopes
3
+ # Handles dynamically creating named scopes for columns. It allows you to do things like:
4
+ #
5
+ # User.first_name_like("ben")
6
+ # User.id_lt(10)
7
+ #
8
+ # Notice the constants in this class, they define which conditions Searchlogic provides.
9
+ #
10
+ # See the README for a more detailed explanation.
11
+ module Conditions
12
+ COMPARISON_CONDITIONS = {
13
+ :equals => [:is, :eq],
14
+ :does_not_equal => [:not_equal_to, :is_not, :not, :ne],
15
+ :less_than => [:lt, :before],
16
+ :less_than_or_equal_to => [:lte],
17
+ :greater_than => [:gt, :after],
18
+ :greater_than_or_equal_to => [:gte],
19
+ }
20
+
21
+ WILDCARD_CONDITIONS = {
22
+ :like => [:contains, :includes],
23
+ :not_like => [],
24
+ :begins_with => [:bw],
25
+ :not_begin_with => [:does_not_begin_with],
26
+ :ends_with => [:ew],
27
+ :not_end_with => [:does_not_end_with]
28
+ }
29
+
30
+ BOOLEAN_CONDITIONS = {
31
+ :null => [:nil],
32
+ :not_null => [:not_nil],
33
+ :empty => [],
34
+ :blank => [],
35
+ :not_blank => [:present]
36
+ }
37
+
38
+ GROUP_CONDITIONS = {
39
+ :in => [],
40
+ :not_in => []
41
+ }
42
+
43
+ CONDITIONS = {}
44
+
45
+ # Add any / all variations to every comparison and wildcard condition
46
+ COMPARISON_CONDITIONS.merge(WILDCARD_CONDITIONS).each do |condition, aliases|
47
+ CONDITIONS[condition] = aliases
48
+ CONDITIONS["#{condition}_any".to_sym] = aliases.collect { |a| "#{a}_any".to_sym }
49
+ CONDITIONS["#{condition}_all".to_sym] = aliases.collect { |a| "#{a}_all".to_sym }
50
+ end
51
+
52
+ CONDITIONS[:equals_any] = CONDITIONS[:equals_any] + [:in]
53
+ CONDITIONS[:does_not_equal_any] = CONDITIONS[:equals_any] + [:not_in]
54
+
55
+ BOOLEAN_CONDITIONS.each { |condition, aliases| CONDITIONS[condition] = aliases }
56
+
57
+ GROUP_CONDITIONS.each { |condition, aliases| CONDITIONS[condition] = aliases }
58
+
59
+ PRIMARY_CONDITIONS = CONDITIONS.keys
60
+ ALIAS_CONDITIONS = CONDITIONS.values.flatten
61
+
62
+ # Is the name of the method a valid condition that can be dynamically created?
63
+ def condition?(name)
64
+ local_condition?(name)
65
+ end
66
+
67
+ private
68
+ def local_condition?(name)
69
+ return false if name.blank?
70
+ scope_names = scopes.keys.reject { |k| k == :scoped }
71
+ scope_names.include?(name.to_sym) || !condition_details(name).nil? || boolean_condition?(name)
72
+ end
73
+
74
+ def boolean_condition?(name)
75
+ column = columns_hash[name.to_s] || columns_hash[name.to_s.gsub(/^not_/, "")]
76
+ column && column.type == :boolean
77
+ end
78
+
79
+ def method_missing(name, *args, &block)
80
+ if details = condition_details(name)
81
+ create_condition(details[:column], details[:condition], args)
82
+ send(name, *args)
83
+ elsif boolean_condition?(name)
84
+ column = name.to_s.gsub(/^not_/, "")
85
+ named_scope name, :conditions => {column => (name.to_s =~ /^not_/).nil?}
86
+ send(name)
87
+ else
88
+ super
89
+ end
90
+ end
91
+
92
+ def condition_details(method_name)
93
+ column_name_matcher = column_names.join("|")
94
+ conditions_matcher = (PRIMARY_CONDITIONS + ALIAS_CONDITIONS).join("|")
95
+
96
+ if method_name.to_s =~ /^(#{column_name_matcher})_(#{conditions_matcher})$/
97
+ {:column => $1, :condition => $2}
98
+ end
99
+ end
100
+
101
+ def create_condition(column, condition, args)
102
+ if PRIMARY_CONDITIONS.include?(condition.to_sym)
103
+ create_primary_condition(column, condition)
104
+ elsif ALIAS_CONDITIONS.include?(condition.to_sym)
105
+ create_alias_condition(column, condition, args)
106
+ end
107
+ end
108
+
109
+ def create_primary_condition(column, condition)
110
+ column_type = columns_hash[column.to_s].type
111
+ skip_conversion = skip_time_zone_conversion_for_attributes.include?(columns_hash[column.to_s].name.to_sym)
112
+ match_keyword = ::ActiveRecord::Base.connection.adapter_name == "PostgreSQL" ? "ILIKE" : "LIKE"
113
+
114
+ scope_options = case condition.to_s
115
+ when /^equals/
116
+ scope_options(condition, column_type, lambda { |a| attribute_condition("#{table_name}.#{column}", a) }, :skip_conversion => skip_conversion)
117
+ when /^does_not_equal/
118
+ scope_options(condition, column_type, "#{table_name}.#{column} != ?", :skip_conversion => skip_conversion)
119
+ when /^less_than_or_equal_to/
120
+ scope_options(condition, column_type, "#{table_name}.#{column} <= ?", :skip_conversion => skip_conversion)
121
+ when /^less_than/
122
+ scope_options(condition, column_type, "#{table_name}.#{column} < ?", :skip_conversion => skip_conversion)
123
+ when /^greater_than_or_equal_to/
124
+ scope_options(condition, column_type, "#{table_name}.#{column} >= ?", :skip_conversion => skip_conversion)
125
+ when /^greater_than/
126
+ scope_options(condition, column_type, "#{table_name}.#{column} > ?", :skip_conversion => skip_conversion)
127
+ when /^like/
128
+ scope_options(condition, column_type, "#{table_name}.#{column} #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :like)
129
+ when /^not_like/
130
+ scope_options(condition, column_type, "#{table_name}.#{column} NOT #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :like)
131
+ when /^begins_with/
132
+ scope_options(condition, column_type, "#{table_name}.#{column} #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :begins_with)
133
+ when /^not_begin_with/
134
+ scope_options(condition, column_type, "#{table_name}.#{column} NOT #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :begins_with)
135
+ when /^ends_with/
136
+ scope_options(condition, column_type, "#{table_name}.#{column} #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :ends_with)
137
+ when /^not_end_with/
138
+ scope_options(condition, column_type, "#{table_name}.#{column} NOT #{match_keyword} ?", :skip_conversion => skip_conversion, :value_modifier => :ends_with)
139
+ when "null"
140
+ {:conditions => "#{table_name}.#{column} IS NULL"}
141
+ when "not_null"
142
+ {:conditions => "#{table_name}.#{column} IS NOT NULL"}
143
+ when "empty"
144
+ {:conditions => "#{table_name}.#{column} = ''"}
145
+ when "blank"
146
+ {:conditions => "#{table_name}.#{column} = '' OR #{table_name}.#{column} IS NULL"}
147
+ when "not_blank"
148
+ {:conditions => "#{table_name}.#{column} != '' AND #{table_name}.#{column} IS NOT NULL"}
149
+ end
150
+
151
+ named_scope("#{column}_#{condition}".to_sym, scope_options)
152
+ end
153
+
154
+ # This method helps cut down on defining scope options for conditions that allow *_any or *_all conditions.
155
+ # Kepp in mind that the lambdas get cached in a method, so you want to keep the contents of the lambdas as
156
+ # fast as possible, which is why I didn't do the case statement inside of the lambda.
157
+ def scope_options(condition, column_type, sql, options = {})
158
+ case condition.to_s
159
+ when /_(any|all)$/
160
+ searchlogic_lambda(column_type, :skip_conversion => options[:skip_conversion]) { |*values|
161
+ return {} if values.empty?
162
+ values.flatten!
163
+ values.collect! { |value| value_with_modifier(value, options[:value_modifier]) }
164
+
165
+ join = $1 == "any" ? " OR " : " AND "
166
+ scope_sql = values.collect { |value| sql.is_a?(Proc) ? sql.call(value) : sql }.join(join)
167
+
168
+ {:conditions => [scope_sql, *expand_range_bind_variables(values)]}
169
+ }
170
+ else
171
+ searchlogic_lambda(column_type, :skip_conversion => options[:skip_conversion]) { |*values|
172
+ values.collect! { |value| value_with_modifier(value, options[:value_modifier]) }
173
+
174
+ scope_sql = sql.is_a?(Proc) ? sql.call(*values) : sql
175
+
176
+ {:conditions => [scope_sql, *expand_range_bind_variables(values)]}
177
+ }
178
+ end
179
+ end
180
+
181
+ def value_with_modifier(value, modifier)
182
+ case modifier
183
+ when :like
184
+ "%#{value}%"
185
+ when :begins_with
186
+ "#{value}%"
187
+ when :ends_with
188
+ "%#{value}"
189
+ else
190
+ value
191
+ end
192
+ end
193
+
194
+ def create_alias_condition(column, condition, args)
195
+ primary_condition = primary_condition(condition)
196
+ alias_name = "#{column}_#{condition}"
197
+ primary_name = "#{column}_#{primary_condition}"
198
+ send(primary_name, *args) # go back to method_missing and make sure we create the method
199
+ (class << self; self; end).class_eval { alias_method alias_name, primary_name }
200
+ end
201
+
202
+ # Returns the primary condition for the given alias. Ex:
203
+ #
204
+ # primary_condition(:gt) => :greater_than
205
+ def primary_condition(alias_condition)
206
+ CONDITIONS.find { |k, v| k == alias_condition.to_sym || v.include?(alias_condition.to_sym) }.first
207
+ end
208
+
209
+ # Returns the primary name for any condition on a column. You can pass it
210
+ # a primary condition, alias condition, etc, and it will return the proper
211
+ # primary condition name. This helps simply logic throughout Searchlogic. Ex:
212
+ #
213
+ # condition_scope_name(:id_gt) => :id_greater_than
214
+ # condition_scope_name(:id_greater_than) => :id_greater_than
215
+ def condition_scope_name(name)
216
+ if details = condition_details(name)
217
+ if PRIMARY_CONDITIONS.include?(name.to_sym)
218
+ name
219
+ else
220
+ "#{details[:column]}_#{primary_condition(details[:condition])}".to_sym
221
+ end
222
+ else
223
+ nil
224
+ end
225
+ end
226
+ end
227
+ end
228
+ end
@@ -0,0 +1,141 @@
1
+ module Searchlogic
2
+ module NamedScopes
3
+ # Handles dynamically creating named scopes for 'OR' conditions. Please see the README for a more
4
+ # detailed explanation.
5
+ module OrConditions
6
+ class NoConditionSpecifiedError < StandardError; end
7
+ class UnknownConditionError < StandardError; end
8
+
9
+ def condition?(name) # :nodoc:
10
+ super || or_condition?(name)
11
+ end
12
+
13
+ def named_scope_options(name) # :nodoc:
14
+ super || super(or_conditions(name).join("_or_"))
15
+ end
16
+
17
+ private
18
+ def or_condition?(name)
19
+ !or_conditions(name).nil?
20
+ end
21
+
22
+ def method_missing(name, *args, &block)
23
+ if conditions = or_conditions(name)
24
+ create_or_condition(conditions, args)
25
+ (class << self; self; end).class_eval { alias_method name, conditions.join("_or_") } if !respond_to?(name)
26
+ send(name, *args)
27
+ else
28
+ super
29
+ end
30
+ end
31
+
32
+ def or_conditions(name)
33
+ # First determine if we should even work on the name, we want to be as quick as possible
34
+ # with this.
35
+ if (parts = split_or_condition(name)).size > 1
36
+ conditions = interpolate_or_conditions(parts)
37
+ if conditions.any?
38
+ conditions
39
+ else
40
+ nil
41
+ end
42
+ end
43
+ end
44
+
45
+ def split_or_condition(name)
46
+ parts = name.to_s.split("_or_")
47
+ new_parts = []
48
+ parts.each do |part|
49
+ if part =~ /^equal_to(_any|_all)?$/
50
+ new_parts << new_parts.pop + "_or_equal_to"
51
+ else
52
+ new_parts << part
53
+ end
54
+ end
55
+ new_parts
56
+ end
57
+
58
+ # The purpose of this method is to convert the method name parts into actual condition names.
59
+ #
60
+ # Example:
61
+ #
62
+ # ["first_name", "last_name_like"]
63
+ # => ["first_name_like", "last_name_like"]
64
+ #
65
+ # ["id_gt", "first_name_begins_with", "last_name", "middle_name_like"]
66
+ # => ["id_gt", "first_name_begins_with", "last_name_like", "middle_name_like"]
67
+ #
68
+ # Basically if a column is specified without a condition the next condition in the list
69
+ # is what will be used. Once we are able to get a consistent list of conditions we can easily
70
+ # create a scope for it.
71
+ def interpolate_or_conditions(parts)
72
+ conditions = []
73
+ last_condition = nil
74
+
75
+ parts.reverse.each do |part|
76
+ if details = condition_details(part)
77
+ # We are a searchlogic defined scope
78
+ conditions << "#{details[:column]}_#{details[:condition]}"
79
+ last_condition = details[:condition]
80
+ elsif association_details = association_condition_details(part, last_condition)
81
+ path = full_association_path(part, last_condition, association_details[:association])
82
+ conditions << "#{path[:path].join("_").to_sym}_#{path[:column]}_#{path[:condition]}"
83
+ last_condition = path[:condition] || nil
84
+ elsif local_condition?(part)
85
+ # We are a custom scope
86
+ conditions << part
87
+ elsif column_names.include?(part)
88
+ # we are a column, use the last condition
89
+ if last_condition.nil?
90
+ raise NoConditionSpecifiedError.new("The '#{part}' column doesn't know which condition to use, if you use an exact column " +
91
+ "name you need to specify a condition sometime after (ex: id_or_created_at_lt), where id would use the 'lt' condition.")
92
+ end
93
+
94
+ conditions << "#{part}_#{last_condition}"
95
+ else
96
+ raise UnknownConditionError.new("The condition '#{part}' is not a valid condition, we could not find any scopes that match this.")
97
+ end
98
+ end
99
+
100
+ conditions.reverse
101
+ end
102
+
103
+ def full_association_path(part, last_condition, given_assoc)
104
+ path = [given_assoc.name]
105
+ part.sub!(/^#{given_assoc.name}_/, "")
106
+ klass = self
107
+ while klass = klass.send(:reflect_on_association, given_assoc.name)
108
+ klass = klass.klass
109
+ if details = klass.send(:association_condition_details, part, last_condition)
110
+ path << details[:association]
111
+ part = details[:condition]
112
+ given_assoc = details[:association]
113
+ elsif details = klass.send(:condition_details, part)
114
+ return { :path => path, :column => details[:column], :condition => details[:condition] }
115
+ end
116
+ end
117
+ { :path => path, :column => part, :condition => last_condition }
118
+ end
119
+
120
+ def create_or_condition(scopes, args)
121
+ scopes_options = scopes.collect { |scope, *args| send(scope, *args).proxy_options }
122
+ # We're using first scope to determine column's type
123
+ scope = named_scope_options(scopes.first)
124
+ column_type = scope.respond_to?(:searchlogic_options) ? scope.searchlogic_options[:type] : :string
125
+ named_scope scopes.join("_or_"), searchlogic_lambda(column_type) { |*args|
126
+ merge_scopes_with_or(scopes.collect { |scope| clone.send(scope, *args) })
127
+ }
128
+ end
129
+
130
+ def merge_scopes_with_or(scopes)
131
+ scopes_options = scopes.collect { |scope| scope.scope(:find) }
132
+ conditions = scopes_options.reject { |o| o[:conditions].nil? }.collect { |o| sanitize_sql(o[:conditions]) }
133
+ scope = scopes_options.inject(scoped({})) { |current_scope, options| current_scope.scoped(options) }
134
+ options = {}
135
+ in_searchlogic_delegation { options = scope.scope(:find) }
136
+ options.delete(:readonly) unless scopes.any? { |scope| scope.proxy_options.key?(:readonly) }
137
+ options.merge(:conditions => "(" + conditions.join(") OR (") + ")")
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,48 @@
1
+ module Searchlogic
2
+ module NamedScopes
3
+ # Handles dynamically creating named scopes for ordering by columns. Example:
4
+ #
5
+ # User.ascend_by_id
6
+ # User.descend_by_username
7
+ #
8
+ # See the README for a more detailed explanation.
9
+ module Ordering
10
+ def condition?(name) # :nodoc:
11
+ super || ordering_condition?(name)
12
+ end
13
+
14
+ private
15
+ def ordering_condition?(name) # :nodoc:
16
+ !ordering_condition_details(name).nil?
17
+ end
18
+
19
+ def method_missing(name, *args, &block)
20
+ if name == :order
21
+ named_scope name, lambda { |scope_name|
22
+ return {} if !condition?(scope_name)
23
+ send(scope_name).proxy_options
24
+ }
25
+ send(name, *args)
26
+ elsif details = ordering_condition_details(name)
27
+ create_ordering_conditions(details[:column])
28
+ send(name, *args)
29
+ else
30
+ super
31
+ end
32
+ end
33
+
34
+ def ordering_condition_details(name)
35
+ if name.to_s =~ /^(ascend|descend)_by_(#{column_names.join("|")})$/
36
+ {:order_as => $1, :column => $2}
37
+ elsif name.to_s =~ /^order$/
38
+ {}
39
+ end
40
+ end
41
+
42
+ def create_ordering_conditions(column)
43
+ named_scope("ascend_by_#{column}".to_sym, {:order => "#{table_name}.#{column} ASC"})
44
+ named_scope("descend_by_#{column}".to_sym, {:order => "#{table_name}.#{column} DESC"})
45
+ end
46
+ end
47
+ end
48
+ end