結合 method_missing、respond_to?、DynamicFinderMatch 封裝、define_method 緩存,實作類 ActiveRecord 的動態查找器 find_by_<attribute>,含測試案例。
class LegislatorDynamicFinderMatch
attr_reader :attribute
def initialize(method_sym)
if method_sym.to_s =~ /^find_by_(.*)$/
@attribute = $1.to_sym
end
end
def match?
!@attribute.nil?
end
end
class Legislator
def self.find(conditions={})
# 實際查詢邏輯
end
def self.method_missing(method_sym, *args, &block)
match = LegislatorDynamicFinderMatch.new(method_sym)
if match.match?
find(match.attribute => args.first)
else
super
end
end
def self.respond_to?(method_sym, include_private=false)
LegislatorDynamicFinderMatch.new(method_sym).match? || super
end
end
def self.method_missing(method_sym, *args, &block)
match = LegislatorDynamicFinderMatch.new(method_sym)
if match.match?
define_dynamic_finder(method_sym, match.attribute)
send(method_sym, *args, &block)
else
super
end
end
protected
def self.define_dynamic_finder(finder, attribute)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{finder}(#{attribute})
find(:#{attribute} => #{attribute})
end
RUBY
end
第二次呼叫 find_by_first_name 直接命中實體方法,不再經過 method_missing。
describe LegislatorDynamicFinderMatch do
describe 'find_by_first_name' do
before { @match = LegislatorDynamicFinderMatch.new(:find_by_first_name) }
it { expect(@match.attribute).to eq(:first_name) }
it { expect(@match).to be_a_match }
end
describe 'zomg' do
before { @match = LegislatorDynamicFinderMatch.new(:zomg) }
it { expect(@match.attribute).to be_nil }
it { expect(@match).not_to be_a_match }
end
end
describe Legislator, 'dynamic find_by_first_name' do
it 'delegates to find(:first_name => name)' do
expect(Legislator).to receive(:find).with(first_name: 'John')
Legislator.find_by_first_name('John')
end
end
DynamicFinderMatch,method_missing/respond_to? 雙方複用,DRY。class_eval 字串插值定義方法,__FILE__/__LINE__ 保留除錯資訊。