searchlogic-donotuse 2.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,299 @@
1
+ = Searchlogic
2
+
3
+ Searchlogic makes using ActiveRecord named scopes easier and less repetitive. It helps keep your code DRY, clean, and simple.
4
+
5
+ == Helpful links
6
+
7
+ * <b>Documentation:</b> http://rdoc.info/projects/binarylogic/searchlogic
8
+ * <b>Repository:</b> http://github.com/binarylogic/searchlogic/tree/master
9
+ * <b>Issues:</b> http://github.com/binarylogic/searchlogic/issues
10
+ * <b>Google group:</b> http://groups.google.com/group/searchlogic
11
+ * <b>Railscast:</b> http://railscasts.com/episodes/176-searchlogic
12
+
13
+ <b>Before contacting me directly, please read:</b>
14
+
15
+ If you find a bug or a problem please post it in the issues section. If you need help with something, please use google groups. I check both regularly and get emails when anything happens, so that is the best place to get help. This also benefits other people in the future with the same questions / problems. Thank you.
16
+
17
+ == Install & use
18
+
19
+ Install the gem from rubyforge:
20
+
21
+ sudo gem install searchlogic
22
+
23
+ Or from github:
24
+
25
+ sudo gem install binarylogic-searchlogic
26
+
27
+ Now just include it in your project and you are ready to go.
28
+
29
+ You can also install this as a plugin:
30
+
31
+ script/plugin install git://github.com/binarylogic/searchlogic.git
32
+
33
+ See below for usage examples.
34
+
35
+ == Search using conditions on columns
36
+
37
+ Instead of explaining what Searchlogic can do, let me show you. Let's start at the top:
38
+
39
+ # We have the following model
40
+ User(id: integer, created_at: datetime, username: string, age: integer)
41
+
42
+ # Searchlogic gives you a bunch of named scopes for free:
43
+ User.username_equals("bjohnson")
44
+ User.username_equals(["bjohnson", "thunt"])
45
+ User.username_equals("a".."b")
46
+ User.username_does_not_equal("bjohnson")
47
+ User.username_begins_with("bjohnson")
48
+ User.username_not_begin_with("bjohnson")
49
+ User.username_like("bjohnson")
50
+ User.username_not_like("bjohnson")
51
+ User.username_ends_with("bjohnson")
52
+ User.username_not_end_with("bjohnson")
53
+ User.age_greater_than(20)
54
+ User.age_greater_than_or_equal_to(20)
55
+ User.age_less_than(20)
56
+ User.age_less_than_or_equal_to(20)
57
+ User.username_null
58
+ User.username_not_null
59
+ User.username_blank
60
+
61
+ Any named scope Searchlogic creates is dynamic and created via method_missing. Meaning it will only create what you need. Also, keep in mind, these are just named scopes, you can chain them, call methods off of them, etc:
62
+
63
+ scope = User.username_like("bjohnson").age_greater_than(20).id_less_than(55)
64
+ scope.all
65
+ scope.first
66
+ scope.count
67
+ # etc...
68
+
69
+ For a complete list of conditions please see the constants in Searchlogic::NamedScopes::Conditions.
70
+
71
+ == Use condition aliases
72
+
73
+ Typing out 'greater_than_or_equal_to' is not fun. Instead Searchlogic provides various aliases for the conditions. For a complete list please see Searchlogic::NamedScopes::Conditions. But they are pretty straightforward:
74
+
75
+ User.username_is(10) # equals
76
+ User.username_eq(10) # equals
77
+ User.id_lt(10) # less than
78
+ User.id_lte(10) # less than or equal to
79
+ User.id_gt(10) # greater than
80
+ User.id_gte(10) # greater than or equal to
81
+ # etc...
82
+
83
+ == Search using scopes in associated classes
84
+
85
+ This is my favorite part of Searchlogic. You can dynamically call scopes on associated classes and Searchlogic will take care of creating the necessary joins for you. This is REALY nice for keeping your code DRY. The best way to explain this is to show you:
86
+
87
+ === Searchlogic provided scopes
88
+
89
+ Let's take some basic scopes that Searchlogic provides for every model:
90
+
91
+ # We have the following relationships
92
+ User.has_many :orders
93
+ Order.has_many :line_items
94
+ LineItem
95
+
96
+ # Set conditions on association columns
97
+ User.orders_total_greater_than(20)
98
+ User.orders_line_items_price_greater_than(20)
99
+
100
+ # Order by association columns
101
+ User.ascend_by_order_total
102
+ User.descend_by_orders_line_items_price
103
+
104
+ This is recursive, you can travel through your associations simply by typing it in the name of the method. Again these are just named scopes. You can chain them together, call methods off of them, etc.
105
+
106
+ === Custom associated scopes
107
+
108
+ Also, these conditions aren't limited to the scopes Searchlogic provides. You can use your own scopes. Like this:
109
+
110
+ LineItem.named_scope :expensive, :conditions => "line_items.price > 500"
111
+
112
+ User.orders_line_items_expensive
113
+
114
+ As I stated above, Searchlogic will take care of creating the necessary joins for you. This is REALLY nice when trying to keep your code DRY, because if you wanted to use a scope like this in your User model you would have to copy over the conditions. Now you have 2 named scopes that are essentially doing the same thing. Why do that when you can dynamically access that scope using this feature?
115
+
116
+ === Uses :joins not :include
117
+
118
+ Another thing to note is that the joins created by Searchlogic do NOT use the :include option, making them <em>much</em> faster. Instead they leverage the :joins option, which is great for performance. To prove my point here is a quick benchmark from an application I am working on:
119
+
120
+ Benchmark.bm do |x|
121
+ x.report { 10.times { Event.tickets_id_gt(10).all(:include => :tickets) } }
122
+ x.report { 10.times { Event.tickets_id_gt(10).all } }
123
+ end
124
+ user system total real
125
+ 10.120000 0.170000 10.290000 ( 12.625521)
126
+ 2.630000 0.050000 2.680000 ( 3.313754)
127
+
128
+ If you want to use the :include option, just specify it:
129
+
130
+ User.orders_line_items_price_greater_than(20).all(:include => {:orders => :line_items})
131
+
132
+ Obviously, only do this if you want to actually use the included objects. Including objects into a query can be helpful with performance, especially when solving an N+1 query problem.
133
+
134
+ == Order your search
135
+
136
+ Just like the various conditions, Searchlogic gives you some very basic scopes for ordering your data:
137
+
138
+ User.ascend_by_id
139
+ User.descend_by_id
140
+ User.ascend_by_orders_line_items_price
141
+ # etc...
142
+
143
+ == Use any or all
144
+
145
+ Every condition you've seen in this readme also has 2 related conditions that you can use. Example:
146
+
147
+ User.username_like_any("bjohnson", "thunt") # will return any users that have either of the strings in their username
148
+ User.username_like_all("bjohnson", "thunt") # will return any users that have all of the strings in their username
149
+ User.username_like_any(["bjohnson", "thunt"]) # also accepts an array
150
+
151
+ This is great for checkbox filters, etc. Where you can pass an array right from your form to this condition.
152
+
153
+ == Combine scopes with 'OR'
154
+
155
+ In the same fashion that Searchlogic provides a tool for accessing scopes in associated classes, it also provides a tool for combining scopes with 'OR'. As we all know, when scopes are combined they are joined with 'AND', but sometimes you need to combine scopes with 'OR'. Searchlogic solves this problem:
156
+
157
+ User.username_or_first_name_like("ben")
158
+ => "username LIKE '%ben%' OR first_name like'%ben%'"
159
+
160
+ User.id_or_age_lt_or_username_or_first_name_begins_with(10)
161
+ => "id < 10 OR age < 10 OR username LIKE 'ben%' OR first_name like'ben%'"
162
+
163
+ Notice you don't have to specify the explicit condition (like, gt, lt, begins with, etc.). You just need to eventually specify it. If you specify a column it will just use the next condition specified. So instead of:
164
+
165
+ User.username_like_or_first_name_like("ben")
166
+
167
+ You can do:
168
+
169
+ User.username_or_first_name_like("ben")
170
+
171
+ Again, these just map to named scopes. Use Searchlogic's dynamic scopes, use scopes on associations, use your own custom scopes. As long as it maps to a named scope it will join the conditions with 'OR'. There are no limitations.
172
+
173
+ == Create scope procedures
174
+
175
+ Sometimes you notice a pattern in your application where you are constantly combining certain named scopes. You want to keep the flexibility of being able to mix and match small named scopes, while at the same time being able to call a single scope for a common task. User searchlogic's scpe procedure:
176
+
177
+ User.scope_procedure :awesome, lambda { first_name_begins_with("ben").last_name_begins_with("johnson").website_equals("binarylogic.com") }
178
+
179
+ All that this is doing is creating a class level method, but what is nice about this method is that is more inline with your other named scopes. It also tells searchlogic that this method is 'safe' to use when using the search method. Ex:
180
+
181
+ User.search(:awesome => true)
182
+
183
+ Otherwise searchlogic will ignore the 'awesome' condition because there is no way to tell that its a valid scope. This is a security measure to keep users from passing in a scope with a named like 'destroy_all'.
184
+
185
+ == Make searching and ordering data in your application trivial
186
+
187
+ The above is great, but what about tying all of this in with a search form in your application? What would be really nice is if we could use an object that represented a single search. Like this...
188
+
189
+ search = User.search(:username_like => "bjohnson", :age_less_than => 20)
190
+ search.all
191
+
192
+ The above is equivalent to:
193
+
194
+ User.username_like("bjohnson").age_less_than(20).all
195
+
196
+ You can set, read, and chain conditions off of your search too:
197
+
198
+ search.username_like => "bjohnson"
199
+ search.age_gt = 2 => 2
200
+ search.id_gt(10).email_begins_with("bjohnson") => <#Searchlogic::Search...>
201
+ search.all => An array of users
202
+ search.count => integer
203
+ # .. etc
204
+
205
+ So let's start with the controller...
206
+
207
+ === Your controller
208
+
209
+ The search class just chains named scopes together for you. What's so great about that? It keeps your controllers extremely simple:
210
+
211
+ class UsersController < ApplicationController
212
+ def index
213
+ @search = User.search(params[:search])
214
+ @users = @search.all
215
+ end
216
+ end
217
+
218
+ It doesn't get any simpler than that.
219
+
220
+ === Your form
221
+
222
+ Adding a search condition is as simple as adding a condition to your form. Remember all of those named scopes above? Just create fields with the same names:
223
+
224
+ - form_for @search do |f|
225
+ = f.text_field :username_like
226
+ = f.select :age_greater_than, (0..100)
227
+ = f.text_field :orders_total_greater_than
228
+ = f.submit
229
+
230
+ When a Searchlogic::Search object is passed to form_for it will add a hidden field for the "order" condition, to preserve the order of the data.
231
+
232
+ === Additional helpers
233
+
234
+ There really isn't a big need for helpers in searchlogic, other than helping you order data. If you want to order your search with a link, just specify the name of the column. Ex:
235
+
236
+ = order @search, :by => :age
237
+ = order @search, :by => :created_at, :as => "Created date"
238
+
239
+ The first one will create a link that alternates between calling "ascend_by_age" and "descend_by_age". If you wanted to order your data by more than just a column, create your own named scopes: "ascend_by_*" and "descend_by_*". The "order" helper is a very straight forward helper, checkout the docs for some of the options.
240
+
241
+ <b>This helper is just a convenience method. It's extremely simple and there is nothing wrong with creating your own. If it doesn't do what you want, copy the code, modify it, and create your own. You could even fork the project, modify it there, and use your own gem.</b>
242
+
243
+ == Use your existing named scopes
244
+
245
+ This is one of the big differences between Searchlogic v1 and v2. What about your existing named scopes? Let's say you have this:
246
+
247
+ User.named_scope :four_year_olds, :conditions => {:age => 4}
248
+
249
+ Again, these are all just named scopes, use it in the same way:
250
+
251
+ User.search(:four_year_olds => true, :username_like => "bjohnson")
252
+
253
+ Notice we pass true as the value. If a named scope does not accept any parameters (arity == 0) you can simply pass it true or false. If you pass false, the named scope will be ignored. If your named scope accepts a parameter, the value will be passed right to the named scope regardless of the value.
254
+
255
+ Now just throw it in your form:
256
+
257
+ - form_for @search do |f|
258
+ = f.text_field :username_like
259
+ = f.check_box :four_year_olds
260
+ = f.submit
261
+
262
+ This really allows Searchlogic to extend beyond what it provides internally. If Searchlogic doesn't provide a named scope for that crazy edge case that you need, just create your own named scope and use it. The sky is the limit.
263
+
264
+ == Pagination (leverage will_paginate)
265
+
266
+ Instead of recreating the wheel with pagination, Searchlogic works great with will_paginate. All that Searchlogic is doing is creating named scopes, and will_paginate works great with named scopes:
267
+
268
+ User.username_like("bjohnson").age_less_than(20).paginate(:page => params[:page])
269
+ User.search(:username_like => "bjohnson", :age_less_than => 20).paginate(:page => params[:page])
270
+
271
+ If you don't like will_paginate, use another solution, or roll your own. Pagination really has nothing to do with searching, and the main goal for Searchlogic v2 was to keep it lean and simple. No reason to recreate the wheel and bloat the library.
272
+
273
+ == Conflicts with other gems
274
+
275
+ You will notice searchlogic wants to create a method called "search". So do other libraries like thinking-sphinx, etc. So searchlogic has a no conflict resolution. If the "search" method is already taken the method will be called "searchlogic" instead. So instead of
276
+
277
+ User.search
278
+
279
+ You would do:
280
+
281
+ User.searchlogic
282
+
283
+ == Under the hood
284
+
285
+ Before I use a library in my application I like to glance at the source and try to at least understand the basics of how it works. If you are like me, a nice little explanation from the author is always helpful:
286
+
287
+ Searchlogic utilizes method_missing to create all of these named scopes. When it hits method_missing it creates a named scope to ensure it will never hit method missing for that named scope again. Sort of a caching mechanism. It works in the same fashion as ActiveRecord's "find_by_*" methods. This way only the named scopes you need are created and nothing more.
288
+
289
+ The search object is just a proxy to your model that only delegates calls that map to named scopes and nothing more. This is obviously done for security reasons. It also helps make form integration easier, by type casting values, and playing nice with form_for. This class is pretty simple as well.
290
+
291
+ That's about it, the named scope options are pretty bare bones and created just like you would manually.
292
+
293
+ == Credit
294
+
295
+ Thanks a lot to {Tyler Hunt}[http://github.com/tylerhunt] for helping plan, design, and start the project. He was a big help.
296
+
297
+ == Copyright
298
+
299
+ Copyright (c) 2009 {Ben Johnson of Binary Logic}[http://www.binarylogic.com], released under the MIT license
@@ -0,0 +1,19 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "searchlogic-donotuse"
8
+ gem.summary = "Searchlogic makes using ActiveRecord named scopes easier and less repetitive."
9
+ gem.description = "Searchlogic makes using ActiveRecord named scopes easier and less repetitive."
10
+ gem.email = "bjohnson@binarylogic.com"
11
+ gem.homepage = "http://github.com/binarylogic/searchlogic"
12
+ gem.authors = ["Ben Johnson of Binary Logic"]
13
+ gem.rubyforge_project = "searchlogic-donotuse"
14
+ gem.add_dependency "activerecord", "2.3.9"
15
+ end
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
19
+ end
@@ -0,0 +1,5 @@
1
+ ---
2
+ :minor: 3
3
+ :patch: 9
4
+ :major: 2
5
+ :build:
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require "searchlogic"
@@ -0,0 +1,40 @@
1
+ require "searchlogic/core_ext/proc"
2
+ require "searchlogic/core_ext/object"
3
+ require "searchlogic/active_record/consistency"
4
+ require "searchlogic/active_record/named_scopes"
5
+ require "searchlogic/named_scopes/conditions"
6
+ require "searchlogic/named_scopes/ordering"
7
+ require "searchlogic/named_scopes/association_conditions"
8
+ require "searchlogic/named_scopes/association_ordering"
9
+ require "searchlogic/named_scopes/alias_scope"
10
+ require "searchlogic/named_scopes/or_conditions"
11
+ require "searchlogic/search"
12
+
13
+ Proc.send(:include, Searchlogic::CoreExt::Proc)
14
+ Object.send(:include, Searchlogic::CoreExt::Object)
15
+
16
+ module ActiveRecord # :nodoc: all
17
+ class Base
18
+ class << self; include Searchlogic::ActiveRecord::Consistency; end
19
+ end
20
+ end
21
+
22
+ ActiveRecord::Base.extend(Searchlogic::ActiveRecord::NamedScopes)
23
+ ActiveRecord::Base.extend(Searchlogic::NamedScopes::Conditions)
24
+ ActiveRecord::Base.extend(Searchlogic::NamedScopes::AssociationConditions)
25
+ ActiveRecord::Base.extend(Searchlogic::NamedScopes::AssociationOrdering)
26
+ ActiveRecord::Base.extend(Searchlogic::NamedScopes::Ordering)
27
+ ActiveRecord::Base.extend(Searchlogic::NamedScopes::AliasScope)
28
+ ActiveRecord::Base.extend(Searchlogic::NamedScopes::OrConditions)
29
+ ActiveRecord::Base.extend(Searchlogic::Search::Implementation)
30
+
31
+ # Try to use the search method, if it's available. Thinking sphinx and other plugins
32
+ # like to use that method as well.
33
+ if !ActiveRecord::Base.respond_to?(:search)
34
+ ActiveRecord::Base.class_eval { class << self; alias_method :search, :searchlogic; end }
35
+ end
36
+
37
+ if defined?(ActionController)
38
+ require "searchlogic/rails_helpers"
39
+ ActionController::Base.helper(Searchlogic::RailsHelpers)
40
+ end
@@ -0,0 +1,32 @@
1
+ module Searchlogic
2
+ module ActiveRecord
3
+ # Active Record is pretty inconsistent with how their SQL is constructed. This
4
+ # method attempts to close the gap between the various inconsistencies.
5
+ module Consistency
6
+ def self.included(klass)
7
+ klass.class_eval do
8
+ alias_method_chain :merge_joins, :searchlogic
9
+ end
10
+ end
11
+
12
+ # In AR multiple joins are sometimes in a single join query, and other times they
13
+ # are not. The merge_joins method in AR should account for this, but it doesn't.
14
+ # This fixes that problem. This way there is one join per string, which allows
15
+ # the merge_joins method to delete duplicates.
16
+ def merge_joins_with_searchlogic(*args)
17
+ joins = merge_joins_without_searchlogic(*args)
18
+ joins = joins.collect { |j| j.is_a?(String) ? j.split(" ") : j }.flatten.uniq
19
+ joins = joins.collect do |j|
20
+ if j.is_a?(String) && !j =~ / (AND|OR) /i
21
+ j.gsub(/(.*) ON (.*) = (.*)/) do |m|
22
+ sorted = [$2,$3].sort
23
+ "#{$1} ON #{sorted[0]} = #{sorted[1]}"
24
+ end
25
+ else
26
+ j
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,60 @@
1
+ module Searchlogic
2
+ module ActiveRecord
3
+ # Adds methods that give extra information about a classes named scopes.
4
+ module NamedScopes
5
+ # Retrieves the options passed when creating the respective named scope. Ex:
6
+ #
7
+ # named_scope :whatever, :conditions => {:column => value}
8
+ #
9
+ # This method will return:
10
+ #
11
+ # :conditions => {:column => value}
12
+ #
13
+ # ActiveRecord hides this internally in a Proc, so we have to try and pull it out with this
14
+ # method.
15
+ def named_scope_options(name)
16
+ key = scopes.key?(name.to_sym) ? name.to_sym : condition_scope_name(name)
17
+
18
+ if key
19
+ eval("options", scopes[key].binding)
20
+ else
21
+ nil
22
+ end
23
+ end
24
+
25
+ # The arity for a named scope's proc is important, because we use the arity
26
+ # to determine if the condition should be ignored when calling the search method.
27
+ # If the condition is false and the arity is 0, then we skip it all together. Ex:
28
+ #
29
+ # User.named_scope :age_is_4, :conditions => {:age => 4}
30
+ # User.search(:age_is_4 => false) == User.all
31
+ # User.search(:age_is_4 => true) == User.all(:conditions => {:age => 4})
32
+ #
33
+ # We also use it when trying to "copy" the underlying named scope for association
34
+ # conditions. This way our aliased scope accepts the same number of parameters for
35
+ # the underlying scope.
36
+ def named_scope_arity(name)
37
+ options = named_scope_options(name)
38
+ options.respond_to?(:arity) ? options.arity : nil
39
+ end
40
+
41
+ # A convenience method for creating inner join sql to that your inner joins
42
+ # are consistent with how Active Record creates them. Basically a tool for
43
+ # you to use when writing your own named scopes. This way you know for sure
44
+ # that duplicate joins will be removed when chaining scopes together that
45
+ # use the same join.
46
+ #
47
+ # Also, don't worry about breaking up the joins or retriving multiple joins.
48
+ # ActiveRecord will remove dupilicate joins and Searchlogic assists ActiveRecord in
49
+ # breaking up your joins so that they are unique.
50
+ def inner_joins(association_name)
51
+ ::ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, association_name, nil).join_associations.collect { |assoc| assoc.association_join }
52
+ end
53
+
54
+ # See inner_joins, except this creates LEFT OUTER joins.
55
+ def left_outer_joins(association_name)
56
+ ::ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, association_name, nil).join_associations.collect { |assoc| assoc.association_join }
57
+ end
58
+ end
59
+ end
60
+ end