• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >ruby > ruby元编程之创建自己的动态方法

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

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了ruby动态壁纸,ruby rose动态图,ruby元编程,ruby元编程 第2版 pdf,ruby编程工具等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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
</div>

那么这个时候调用

Legislator.respond_to?(:find_by_first_name) 
</div>

将会提示错误,那么继续
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
</div>

正如代码注释所述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
</div>

缓存 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
</div>

测试

测试部分如下:
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
</div>

下面是 RSpec 例子:

代码如下:</div>

您可能想查找下面的文章:

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

相关文章

  • Ruby 魔法 学习笔记之一
  • ruby 标准类型总结
  • 详解组合模式的结构及其在Ruby设计模式编程中的运用
  • 一个简单的Ruby可逆加密解密类
  • Ruby的基础语法入门学习教程
  • 简单介绍Ruby on Rails对PostgreSQL数组类型的支持
  • Ruby简明教程之方法(Method)介绍
  • Ruby实现批量对文件增加前缀代码分享
  • 使用Ruby实现简单的事物驱动的web应用的教程
  • 使用Ruby程序实现web信息抓取的教程

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Ruby中调用执行shell命令的6种方法
    • Ruby包管理器gem常用命令
    • mac os gem安装json出现error failed的解决办法
    • Ruby的语法和语言特性总结
    • 深入剖析Ruby设计模式编程中对命令模式的相关使用
    • Ruby on Rails网站项目构建简单指南
    • 提升Ruby on Rails性能的几个解决方案
    • 详解Ruby设计模式编程中对单例模式的运用
    • ruby声明式语法的实现例子
    • 详解组合模式的结构及其在Ruby设计模式编程中的运用

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有