Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Move search methods to be evaluated when the class is loaded

  • Loading branch information...
commit c2975124e11677825481ced9539f16f0cb0640de 1 parent 48b66ef
@radar authored
View
13 lib/searcher.rb
@@ -13,16 +13,3 @@ def self.classes
ActiveRecord::Base.extend(Searcher::ClassMethods)
-ActiveSupport.on_load(:after_initialize) do
- Searcher.classes.each do |klass|
- table = klass.arel_table
- klass.searcher[:labels].each do |name, config|
- association = klass.reflect_on_association(config[:from])
- association_table = association.klass.arel_table
- if [:has_and_belongs_to_many, :belongs_to].include?(association.macro)
- scope = lambda { |q, field| klass.joins(config[:from]).where(association_table[field].eq(q)) }
- klass.scope "by_#{name}", scope
- end
- end
- end
-end
View
13 lib/searcher/class_methods.rb
@@ -4,7 +4,16 @@ module Searcher
module ClassMethods
def searcher(&block)
Searcher.classes << self unless Searcher.classes.include?(self)
- @config ||= Searcher::Config.new.instance_exec(&block)
+ @config = Searcher::Config.new.instance_exec(&block)
+ table = arel_table
+ @config[:labels].each do |name, config|
+ association = reflect_on_association(config[:from])
+ association_table = association.klass.arel_table
+ if [:has_and_belongs_to_many, :belongs_to].include?(association.macro)
+ scope = lambda { |q, field| joins(config[:from]).where(association_table[field].eq(q)) }
+ self.scope "by_#{name}", scope
+ end
+ end
end
def search(query)
@@ -22,4 +31,4 @@ def search(query)
result || klass.all
end
end
-end
+end
View
16 spec/fixtures/models.rb
@@ -1,3 +1,11 @@
+class Tag < ActiveRecord::Base
+ has_and_belongs_to_many :tickets
+end
+
+class State < ActiveRecord::Base
+ has_many :tickets
+end
+
class Ticket < ActiveRecord::Base
has_and_belongs_to_many :tags
belongs_to :state
@@ -8,14 +16,6 @@ class Ticket < ActiveRecord::Base
end
end
-class Tag < ActiveRecord::Base
- has_and_belongs_to_many :tickets
-end
-
-class State < ActiveRecord::Base
- has_many :tickets
-end
-
#############
### SEEDS ###
#############
Please sign in to comment.
Something went wrong with that request. Please try again.