萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 元編程動態定義 find_by_* 方法完整實作

結合 method_missing、respond_to?、DynamicFinderMatch 封裝、define_method 緩存,實作類 ActiveRecord 的動態查找器 find_by_<attribute>,含測試案例。

核心類別:DynamicFinderMatch


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。

RSpec 測試範例


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__ 保留除錯資訊。
  • 緩存機制將 O(方法數) 降為 O(熱點方法數),記憶體可控。
copyright © 萬盛學電腦網 all rights reserved