【问题标题】:Using Thinking Sphinx and staying DRY (Don't Repeat Yourself)使用 Thinking Sphinx 并保持干燥(不要重复自己)
【发布时间】:2010-12-21 21:57:39
【问题描述】:

在我正在处理的大型项目中,我们有许多模型要索引和搜索。我发现自己一遍又一遍地重复事情......并且知道当我们稍后进行更改时这可能会很糟糕!

在使用 Thinking Sphinx 时,有没有一种保持代码干燥的好方法?特别是,我要索引的每个模型中都有以下代码块:

define_index do
  ... # model specific code goes here
  set_property :delta => true
  has :created_at
end

sphinx_scope(:only_active) do
  { :conditions => { :status => 1 } }
end

我预计随着项目的发展,这个通用代码的大小和功能都会增长......更不用说可能会修复错误。所以很明显我想把这一点排除在外。我希望能够做类似的事情:

define_index_with_common_settings do
  ... # model specific code goes here
end

并自动将公共索引属性包含在索引中...并定义公共搜索相关方法和范围。

这可能吗?是怎么做到的?

【问题讨论】:

    标签: ruby-on-rails dry thinking-sphinx


    【解决方案1】:

    你总是可以创建一个 mixin 来做到这一点:

    module CommonSphinxIndexSettings
      extend ActiveSupport::Concern
      module ClassMethods
        def define_index_with_common_settings
          yield self
          set_property :delta => true
          has :created_at
        end
    
        sphinx_scope(:only_active) do
          { :conditions => { :status => 1 } }
        end
      end
    end
    

    然后添加一个初始化器以将其包含在 AR 中:

    ActiveRecord::Base.send :include, CommonSphinxIndexSettings
    

    这应该保持一切干燥!

    编辑:我做了一个小改动(将 self 传递给 yield 调用),这很重要,因为 ThinkingSphinx 使用的元编程类型。此解决方案有其局限性,但对于大多数情况应该足够好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2023-03-08
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      相关资源
      最近更新 更多