毕竟,我最终破解了ActiveRecord::Relation
's ,结果并没有变得太丑陋。method_missing
这是从头到尾的完整过程。
我的 gem 定义了一个Interceptor
类,旨在成为开发人员可以子类化的 DSL。该对象从 a或 a接收一些root
ARel,并在渲染之前进一步操作查询。Model
Relation
# 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