RoR - MetaProgramming

ruby是动态语言,它有动态语言的优势与劣势

动态语言,像python与ruby 你不用提前去定义method - they need to only be "found" when invoked

calling method dynamically:

class Dog
    def bark
         puts "Woof, woof!‘
    end
    def greet(greeting)
        puts greeting
    end
end

dog = Dog.new
dog.bark # => Woof, woof!
dog.send("bark") # => Woof, woof!
dog.send(:bark) # => Woof, woof!
method_name = :bark
dog.send method_name # => Woof, woof!

dog.send(:greet, "hello") # => hello

  Dynamic Dispatch:

  不需要call method 用 xxx.xxx

  能用string和symbol call methods dynamically

优点:*can decide at runtime which methods to call

*The code doesn‘t have to find out until runtime which method it needs to call

Dynamic method:

class Whatever
    define_method :make_it_up do
        puts "Whatever..."
    end
end

whatever = Whatever.new
whatever.make_it_up # => Whatever...

写动态方法能有效降低code量

require_relative ‘store‘
class ReportingSystem 

    def initialize
        @store = Store.new
        @store.methods.grep(/^get_(.*)_desc/) { ReportingSystem.define_report_method_for $1 )
    end

    def self.define_repot_methods_for (item)
        define_method ("get_#{item}_desc") {@store.send("get_#{item}_desc) }
        define_method ("get_#{item}_price") {@store.send("get_#{item}_desc) }
    end
end

r3 = ReportingSystem.new
puts "#{rs.get_piano_desc} costs #{rs.get_piano_price.to_s.ljust(6.‘0‘)}"

# => Excellent piano costs 120.00

Ghost method:

如果我们使用了不存在的method,会自动跳转到method_missing  method,不过method_missing 可以被复写:

class Mystery
    #no_methods defined
    def method_missing (method, *args)
        puts "Looking for..."
        puts "\"#{method}\" with params {#{args.join(‘,‘)}} ?"
        puts "Sorry... He is on vacation... "
        yield "Ended up in method_missing" if block_given?
    end
end 

m = Mystery.new
m.solve_mystery("abc", 123123) do |answer|
    puts "And the answer is: #{answer}"
end

# =>  Looking for...
# =>  "solve_mystery" with params (abc,123123) ?
# =>  Sorry... He is on vacation...
# =>  And the answer is: Ended up in method_missing

* method_missing gives you the power to "fake" the methods

* 这被叫做ghost methods 是因为 它并不真正意义上的存在

*ruby built-in classes use method_missing and dynamic methods all over the place...

Struct and OpenStruct:

Struct: 特定类的生成器,每个类都被定义为保存一组变量及其访问器(动态
方法)

OpenStruct: 对象(类似于Struct),其属性在第一次分配时动态创建(“Ghost方法”)。

Customer = Struct.new(:name, :address) do #block is optional
    def to_s
        "#{name} lives at #{address}"
    end
end
jim = Customer.new("Jim", "-1000 wall Street")
puts jim # => Jim lives at -1000 wall Street

require ‘ostruct‘ # => need to require ostruct for OpenStruct 

some_obj = OpenStruct.new(name: "Joe", age: 15)
some_obj.sure = "three"
some_obj.really = "yes, it is true"
some_obj.not_only_strings = 10
puts "#{some_obj.name} #{some_obj.age} #{some_obj.really}"
#=> Joe 15 yes,it is true

method_missing and Performance:

因为调用是直接的,所以可能会慢一些,但大多数情况下不影响。

如果考虑响应速度的话,可以考虑hybird approach

*Define a real method from inside method missing after an attempted ‘call’

Ghost methods allow you to call methods as if they are there even though they are not
Method behavior can be defined at runtime , for example based on database columns existing or not .

原文地址:https://www.cnblogs.com/vixennn/p/10695260.html

时间: 2024-10-19 12:17:39

RoR - MetaProgramming的相关文章

ROR 环境的 搭建

1)安装RUBY:从 http://www.ruby-lang.org/en/ 下载 ruby182-15.exe,安装Ruby.ruby -v 看是否安装成功.2)安装RAILS框架 :gem install rails --remotesrails -v 看版本号号,看是否安装成功.3)安装 J2SDK 和Eclipse: 我安装了语言文件,用eclipse.exe -nl zh 实现中文化.环境变量: PATH:C:/j2sdk1.4.2_02/bin: 加入CLASSPATH : C:/

Template Metaprogramming with Modern C++: Introduction

Template Metaprogramming with Modern C++: Introduction Posted on September 10, 2014 by Manu Sánchez Template Metaprogramming with Modern C++: Introduction Any sufficiently complex C++ code is indistinguishable from trolling Arthur C. Clarke Preface T

ror笔记2

ror 学习笔记2 在rails app的 config 文件夹中新建unicorn.rb内容如下 worker_processes 2 working_directory "/home/mage/boleht" listen "/tmp/unicorn.boleht.sock" listen 19555, :tcp_nopush => true timeout 120 pid "/home/mage/boleht/tmp/pids/unicorn.

汇编移位: SHL、SHR、SAL、SAR、ROL、ROR、RCL、RCR

SHL.SHR.SAL.SAR: 移位指令 ;SHL(Shift Left):      逻辑左移 ;SHR(Shift Right):      逻辑右移 ;SAL(Shift Arithmetic Left): 算术左移 ;SAR(Shift Arithmetic Right): 算术右移 ;其中的 SHL 和 SAL 相同, 但 SHR 和 SAR 不同. ;SHL.SAL: 每位左移, 低位补 0, 高位进 CF ;SHR  : 每位右移, 低位进 CF, 高位补 0 ;SAR  : 每

最新RubyMine2016.2开发Ruby ON Rails(ROR)程序的流程

1.RubyMine新建ROR工程 File->New Project ? ? 选择Rails下的"New Application" ? ? 点击OK 后生成ROR项目 ? ? ? ? 2.添加 Controller 新建项目后,在在工程名上右键->新建 ? ? 填入Controller的名字,点击OK即可 ? ? 生成Controller后,会自动为app目录下的文件夹添加如下四个文件并直接在编辑器中打开,第一个最常用 ? ? 3.添加程序 在上面第一个文件里自定义一个过

Ror初学笔记

Ror正在以惊人的速度增长着,特别是在常常光顾JavaEye的时候发现Ror已经在国内有非常好的基础了,当然要凑个热闹尝尝鲜 咯. 眼下国内Ror的中文资料还是非常少的,到网上找找就仅仅有Eiffel Qiu的 Ruby on Rails实践(下面简称为Ror实践),想必是假设有朝一日Ror成就大业了,那么国内肯定本文的作者肯定就是国内Ror的开山鼻祖咯.毕竟Ror是新事务,像我这样的仅仅能勉强看看E文的人肯定非常多的,假设直接就拿来那种大部头的文档来读,预计是非常难入门了.所以大家都要好好学习

SHL SHR, SAL SAR, ROL ROR

//____逻辑移动是针对无符号数的______________________________________________ 逻辑左移 SHL  逻辑右移 SHR: unsigned int i = 0x1234; unsigned int j = 0; j = i >> 8;    //右移, 执行后 j = 0x12; j = i << 8;    //左移, 执行后 j = 0x123400;//_____算术移动是针对有符号数的_____________________

CppCon - Modern Template Metaprogramming 杂记

2014年底才看到github和channel9上有CppCon2014的视频和资料,顿时激动不已.最近小生也一直在研习CppCon2014中令人兴奋的内容.这篇鄙文就是小生学习了<Modern Template Metaprogramming>之后,有对Unevaluated Operands更深刻的理解,有感而写. C++98标准中的Unevaluated Operands,只有sizeof操作符.C++11又引入了decltype,typeid和noexcept.Unevaluated

Centos系统搭建ror平台搭建

本文系统Centos6.5 x64 Ruby On Rails是一个用Ruby语言写的开源Web框架,和J2EE,PHP等类似.Ruby On Rails是一个非常优美的Web开发框架,并且融入了敏捷开发的精髓:约定大于配置.你会发现,它真的是一个非常优美的框架!今天我们介绍如何在Centos下搭建Ruby On Rails开发环境. Tips: Ruby Version Manager,Ruby版本管理器,包括Ruby的版本管理和Gem库管理(gemset).目前支持Ruby的大多数版本,有