ruby元编程之创建自己的动态方法

 更新时间:2015年05月26日 09:24:09   投稿:junjie  
这篇文章主要介绍了ruby元编程之创建自己的动态方法,本文讲解使用method_missing和respond_to?创建自己的动态方法,需要的朋友可以参考下

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

respond_to? 并不如method_missing出名,常用在当需要确认一个回馈对象需要确认,以便不会因为没有反馈对象,而导致后面的调用出现错误。

下面是一个应用这两者的例子:

示例

我们有类Legislator class,现在,想要给它加一个find_by_first_name('John')的动态调用。实现find(:first_name => 'John')的功能。

复制代码 代码如下:

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?(:find_by_first_name) 

将会提示错误,那么继续

复制代码 代码如下:

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?(method_sym, include_private = false)
    if method_sym.to_s =~ /^find_by_(.*)$/
      true
    else
      super
    end
  end
end

正如代码注释所述respond_to?需要两个参数,如果,你没有提供将会产生ArgumentError。

相关反射 DRY

如果我们注意到了这里有重复的代码。我们可以参考ActiveRecord的实现封装在ActiveRecord::DynamicFinderMatch,以便避免在method_missing和respond_to?中重复。

复制代码 代码如下:

class LegislatorDynamicFinderMatch
  attr_accessor :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.method_missing(method_sym, *arguments, &block)
    match = LegislatorDynamicFinderMatch.new(method_sym)
    if match.match?
      find(match.attribute => arguments.first)
    else
      super
    end
  end

  def self.respond_to?(method_sym, include_private = false)
    if LegislatorDynamicFinderMatch.new(method_sym).match?
      true
    else
      super
    end
  end
end

缓存 method_missing

重复多次的method_missing可以考虑缓存。

另外一个我们可以向ActiveRecord 学习的是,当定义method_missing的时候,发送 now-defined方法。如下:

复制代码 代码如下:

class Legislator   
  def self.method_missing(method_sym, *arguments, &block)
    match = LegislatorDynamicFinderMatch.new(method_sym)
    if match.match?
      define_dynamic_finder(method_sym, match.attribute)
      send(method_sym, arguments.first)
    else
      super
    end
  end
 
  protected
 
  def self.define_dynamic_finder(finder, attribute)
    class_eval <<-RUBY
      def self.#{finder}(#{attribute})        # def self.find_by_first_name(first_name)
        find(:#{attribute} => #{attribute})   #   find(:first_name => first_name)
      end                                     # end
    RUBY
  end
end

测试

测试部分如下:

复制代码 代码如下:

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语言中的String深入理解

    Ruby语言中的String深入理解

    在java中,对于字面量的字符串,jvm内部维持一张表,因此如果在java中,str1和str2是同一个String对象。而在Ruby中, str1和str2是完全不同的对象。
    2011-01-01
  • RUBY文档中心-学习开始

    RUBY文档中心-学习开始

    RUBY文档中心-学习开始...
    2007-11-11
  • 实例讲解Ruby中的五种变量

    实例讲解Ruby中的五种变量

    这篇文章主要介绍了Ruby中的五种变量,并用实例讲解了其用法,是Ruby学习当中的基础知识,需要的朋友可以参考下
    2015-04-04
  • Ruby中require、load、include、extend的区别介绍

    Ruby中require、load、include、extend的区别介绍

    这篇文章主要介绍了Ruby中require、load、include、extend的区别介绍,require、load用于文件,如.rb等等结尾的文件,include、load则用于包含一个文件中的模块,需要的朋友可以参考下
    2015-05-05
  • redis集群搭建教程及遇到的问题处理

    redis集群搭建教程及遇到的问题处理

    本文主要给大家讲诉的是如何搭建redis集群的方法以及在此过程中需要注意的问题,非常不错,推荐给大家,有需要的小伙伴可以来参考下
    2017-09-09
  • Ruby连接使用windows下sql server数据库代码实例

    Ruby连接使用windows下sql server数据库代码实例

    这篇文章主要介绍了Ruby连接使用windows下sql server数据库代码实例,本文直接给出实现代码,而且给出了两种实现和access数据库的实现代码,需要的朋友可以参考下
    2015-05-05
  • Ruby程序中创建和解析XML文件的方法

    Ruby程序中创建和解析XML文件的方法

    这篇文章主要介绍了Ruby程序中创建和解析XML文件的方法,创建用builder库,解析用ReXML库,需要的朋友可以参考下
    2015-11-11
  • Ruby初学笔记之Hello World

    Ruby初学笔记之Hello World

    这篇文章主要介绍了Ruby初学笔记之Hello World,本文是一篇Ruby自学笔记,本文分别用普通方法、函数、类输出Hello World,从一个一个的例子中了解Ruby编程,需要的朋友可以参考下
    2015-06-06
  • 简单对比分析Ruby on Rails 和 Laravel

    简单对比分析Ruby on Rails 和 Laravel

    web应用程序开发中两个相对而言更加流行的框架是 Ruby on Rails 和 Laravel. 它们两个都是非常成熟的项目,已经面世相当长一段时间了 .
    2014-07-07
  • 几个加速Ruby on Rails的编程技巧

    几个加速Ruby on Rails的编程技巧

    这篇文章主要介绍了几个加速Ruby on Rails的编程技巧,本文来自于IBM官方网站技术文档,需要的朋友可以参考下
    2015-04-04

最新评论