2

在我正在制作的 gem 中,我想允许开发人员以经典的 Devise 语法将我编写的类方法添加interceptor到模型中,我们称之为模型:

class User < ActiveRecord::Base
  has_interceptor
end

这允许您调用User.interceptor,它返回一个Interceptor对象,该对象通过Squeelgem 查询数据库来做一些神奇的事情。都好。

但是,我想首先找到一种允许开发人员确定拦截器执行的查询范围的优雅方式。这可以通过允许interceptor接受ActiveRecord::Relation和链接Squeel来实现,否则会退回到模型上。此实现的工作原理如下:

# Builds on blank ARel from User:
User.interceptor.perform_magic
#=> "SELECT `users`.* FROM `users` WHERE interceptor magic"

# Build on scoped ARel from Relation:
User.interceptor( User.where('name LIKE (?)', 'chris') ).perform_magic
#=> "SELECT `users`.* FROM `users`  WHERE `users`.`name` LIKE 'chris' AND  interceptor magic"

这是有效的,但丑陋的。我真正想要的是:

# Build on scoped ARel:
User.where('name LIKE (?)', 'chris').interceptor.perform_magic
#=> "SELECT `users`.* FROM `users`  WHERE `users`.`name` LIKE 'chris' AND  interceptor magic"

本质上,我想“接入”ActiveRecord::Relation链并窃取它的 ARel,将其传递到我的Interceptor对象中以在我评估它之前对其进行修改。但是我能想到的每一种方法都涉及到如此可怕的代码,我知道如果我实现它,上帝会杀了一只小猫。我不需要我手上的血。帮我救一只小猫?

问题:

增加了我的并发症,

class User < ActiveRecord::Base
  has_interceptor :other_interceptor_name
end

允许你调用User.other_interceptor_name,模型可以有多个拦截器。它运作良好,但使用method_missing比平常更糟糕的想法。

4

1 回答 1

1

毕竟,我最终破解了ActiveRecord::Relation's ,结果并没有变得太丑陋。method_missing这是从头到尾的完整过程。

我的 gem 定义了一个Interceptor类,旨在成为开发人员可以子类化的 DSL。该对象从 a或 a接收一些rootARel,并在渲染之前进一步操作查询。ModelRelation

# gem/app/interceptors/interceptor.rb
class Interceptor
  attr_accessor :name, :root, :model
  def initialize(name, root)
    self.name = name
    self.root = root
    self.model = root.respond_to?(:klass) ? root.klass : root
  end
  def render
    self.root.apply_dsl_methods.all.to_json
  end
  ...DSL methods...
end

实施的:

# sample/app/interceptors/user_interceptor.rb
class UserInterceptor < Interceptor
  ...DSL...
end

然后我给模型has_interceptor定义新拦截器并构建interceptors映射的方法:

# gem/lib/interceptors/model_additions.rb
module Interceptor::ModelAdditions

  def has_interceptor(name=:interceptor, klass=Interceptor)
    cattr_accessor :interceptors unless self.respond_to? :interceptors
    self.interceptors ||= {}
    if self.has_interceptor? name
      raise Interceptor::NameError,
        "#{self.name} already has a interceptor with the name '#{name}'. "\
        "Please supply a parameter to has_interceptor other than:"\
        "#{self.interceptors.join(', ')}"
    else
      self.interceptors[name] = klass
      cattr_accessor name
      # Creates new Interceptor that builds off the Model
      self.send("#{name}=", klass.new(name, self))
    end
  end

  def has_interceptor?(name=:interceptor)
    self.respond_to? :interceptors and self.interceptors.keys.include? name.to_s
  end

end

ActiveRecord::Base.extend Interceptor::ModelAdditions

实施的:

# sample/app/models/user.rb
class User < ActiveRecord::Base
  # User.interceptor, uses default Interceptor Class
  has_interceptor
  # User.custom_interceptor, uses custom CustomInterceptor Class
  has_interceptor :custom_interceptor, CustomInterceptor

  # User.interceptors #show interceptor mappings
  #=> {
  #     interceptor: #<Class:Interceptor>,
  #     custom_interceptor: #<Class:CustomInterceptor>
  #   }
  # User.custom_interceptor #gets an instance
  #=> #<CustomInterceptor:0x005h3h234h33>
end

仅凭这一点,您就可以调用 User.interceptor 并构建Interceptor一个干净的查询作为所有拦截器查询操作的根。但是,通过更多的努力,我们可以扩展ActiveRecord::Relation,以便您可以将拦截器方法作为范围链中的端点调用:

# gem/lib/interceptor/relation_additions.rb
module Interceptor::RelationAdditions

  delegate :has_interceptor?, to: :klass

  def respond_to?(method, include_private = false)
    self.has_interceptor? method
  end

protected

  def method_missing(method, *args, &block)
    if self.has_interceptor? method
      # Creates new Interceptor that builds off of a Relation
      self.klass.interceptors[method.to_s].new(method.to_s, self)
    else
      super
    end
  end

end

ActiveRecord::Relation.send :include, Interceptor::RelationAdditions

现在,将在您在模型上构建的任何查询之上User.where('created_at > (?)', Time.current - 2.weeks).custom_interceptor应用 DSL 中设置的所有范围。Interceptor

于 2012-12-03T20:24:25.637 回答