ruby-on-rails – 如何覆盖lib / spree / search / base.rb

我需要覆盖此类中的get_products_conditions_for方法,这样做的最佳方法是什么?

我尝试将其添加到初始化程序中:

Spree::Search::Base.class_eval do
    def get_products_conditions_for(base_scope, query)
      base_scope.like_any([:name, :description], query.split) | base_scope.joins("JOIN taggings on taggings.taggable_id = spree_products.id JOIN tags on tags.id = taggings.tag_id").where("tags.name = ?", query.split)
    end
end

启动服务器时导致此错误:未初始化的常量Spree :: Search(NameError)

我也尝试将其添加到“/lib/spree/search/base.rb”和“/lib/spree/search/tags_search.rb”

module Spree::Search
  class TagsSearch < Spree::Search::Base

    def get_products_conditions_for(base_scope, query)
      base_scope.like_any([:name, :description], query.split) | base_scope.joins("JOIN taggings on taggings.taggable_id = spree_products.id JOIN tags on tags.id = taggings.tag_id").where("tags.name = ?", query.split)
    end

  end
end

然后Spree :: Config.searcher = application.rb中的TagsSearch …

我甚至尝试通过在应用程序内的相同目录结构中放置副本来完全替换文件,或者没有任何反应,或者我得到上述错误…

我要做的是集成acts_as_taggable_on,这已经完成并正常工作,但搜索显然不会返回这些标签的结果……

编辑:好的,所以在Steph的回答之后我尝试过:

module Spree::Search
  class TagsSearch < Spree::Search::Base

    def get_products_conditions_for(base_scope, query)
      base_scope.like_any([:name, :description], query.split) | base_scope.joins("JOIN taggings on taggings.taggable_id = spree_products.id JOIN tags on tags.id = taggings.tag_id").where("tags.name = ?", query.split)
    end

  end
end

在app / models / search / tags_search.rb和Steph的lib / spree / search / tags_search.rb中的代码建议

还有这个:

config.to_prepare do
    Spree::Core::Search::Base.send(:include, TagsSearch)
  end

在config / environments / development.rb中

启动服务器时会导致以下结果:

未初始化的常量TagsSearch(NameError)

最佳答案

I need to override the get_products_conditions_for method in this class, what’s the best way of doing this?

在这种特殊情况下,我继承了该类并覆盖了所需的方法.

和施普雷3一样,

>在config / initializers / spree.rb中,Spree.config块config.searcher_class = Spree :: MySearch
>使用以下内容创建文件lib / spree / my_search.rb:

module Spree
  class MySearch < Spree::Core::Search::Base
    def method_to_be_overridden
      # Your new definition here
    end
  end
end

注意:以上是修改Spree中搜索者类的规定方法

点赞