method_missing是Ruby元编程(metaprogramming)常用的手法。基本思想是通过实现调用不存在的方法,以便进行回调。典型的例子是:ActiveRecord的动态查找(dynamic finder)。例如:我们有email属性那么就可以调用User.find_by_email('joe@example.com'),虽然, ActiveRecord::Base并没有一个叫做find_by_email的方法。

respond_to"codetitle">复制代码 代码如下:
class Legislator
  #假设这是一个真实的实现
  def find(conditions = {})
  end
 
  #在本身定义毕竟这是他的方法
  def self.method_missing(method_sym, *arguments, &block)
    # the first argument is a Symbol, so you need to_s it if you want to pattern match
    if method_sym.to_s =~ /^find_by_(.*)$/
      find($1.to_sym => arguments.first)
    else
      super
    end
  end
end

那么这个时候调用

复制代码 代码如下:
Legislator.respond_to"codetitle">复制代码 代码如下:
class Legislator
  # 省略
 
  # It's important to know Object defines respond_to to take two parameters: the method to check, and whether to include private methods
  # http://www.ruby-doc.org/core/classes/Object.html#M000333
  def self.respond_to"codetitle">复制代码 代码如下:
class LegislatorDynamicFinderMatch
  attr_accessor :attribute
  def initialize(method_sym)
    if method_sym.to_s =~ /^find_by_(.*)$/
      @attribute = $1.to_sym
    end
  end
 
  def match"codetitle">复制代码 代码如下:
class Legislator   
  def self.method_missing(method_sym, *arguments, &block)
    match = LegislatorDynamicFinderMatch.new(method_sym)
    if match.match"codetitle">复制代码 代码如下:
describe LegislatorDynamicFinderMatch do
  describe 'find_by_first_name' do
    before do
      @match = LegislatorDynamicFinderMatch.new(:find_by_first_name)
    end
     
    it 'should have attribute :first_name' do
      @match.attribute.should == :first_name
    end
   
    it 'should be a match' do
      @match.should be_a_match
    end
  end
 
  describe 'zomg' do
    before do
      @match = LegislatorDynamicFinderMatch(:zomg)
    end
   
    it 'should have nil attribute' do
      @match.attribute.should be_nil
    end
   
    it 'should not be a match' do
      @match.should_not be_a_match
    end
  end
end

下面是 RSpec 例子:

复制代码 代码如下:
describe Legislator, 'dynamic find_by_first_name' do 
  it 'should call find(:first_name => first_name)' do 
    Legislator.should_receive(:find).with(:first_name => 'John') 
     
    Legislator.find_by_first_name('John') 
  end 
end

标签:
ruby,元编程,创建自己的动态方法

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com

评论“ruby元编程之创建自己的动态方法”

暂无“ruby元编程之创建自己的动态方法”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。