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 .
RoR - MetaProgramming的更多相关文章
- C++模板元编程(C++ template metaprogramming)
实验平台:Win7,VS2013 Community,GCC 4.8.3(在线版) 所谓元编程就是编写直接生成或操纵程序的程序,C++ 模板给 C++ 语言提供了元编程的能力,模板使 C++ 编程变得 ...
- .Net元编程【Metaprogramming in NET】 序-翻译
最近在看这本书,比较实用.抽点时间把公开的部分内容简单的翻译了一下,下文是序部分. 书的具体地址为: http://www.amazon.cn/Metaprogramming-in-NET-Hazza ...
- ror 在windows下开发的坑
虽然知道ror在windows下的坑很多很多,但是目前没有先将就入门学习,也不折腾了.后面等待新机器来了,用linux来搭平台,先记录一下遇到的坑. 1.views/layouts/applicati ...
- 最新RubyMine2016.2开发Ruby ON Rails(ROR)程序的流程
1.RubyMine新建ROR工程 File->New Project 选择Rails下的"New Application" 点击OK 后生成ROR项目 ...
- ROR 环境的 搭建
1)安装RUBY:从 http://www.ruby-lang.org/en/ 下载 ruby182-15.exe,安装Ruby.ruby -v 看是否安装成功.2)安装RAILS框架 :gem in ...
- CppCon - Modern Template Metaprogramming 杂记
2014年底才看到github和channel9上有CppCon2014的视频和资料,顿时激动不已.最近小生也一直在研习CppCon2014中令人兴奋的内容.这篇鄙文就是小生学习了<Modern ...
- Ror初学笔记
Ror正在以惊人的速度增长着,特别是在常常光顾JavaEye的时候发现Ror已经在国内有非常好的基础了,当然要凑个热闹尝尝鲜 咯. 眼下国内Ror的中文资料还是非常少的,到网上找找就仅仅有Eiffel ...
- Ruby on Rails (ROR)类书籍
Ruby on Rails (ROR)类书籍下载地址及其他(整理) Ruby on Rails 如此之热,忍不住也去看了看热闹,现在把一些相关的电子图书下载地址整理下,方便有兴趣的朋友. 2006-0 ...
- javascript加RoR实现JSONP
我们知道不同域中的js代码受同源策略的限制,不同域中的AJAX同样受此限制,不过使用html中的script远程脚本可以跳过该限制,下面我们实际看一下利用RoR和js如何实现所谓的JSONP. 这里只 ...
随机推荐
- AYUI -AYUI风格的 超美 百度网盘8.0
2017-03-23 19:18:43 (截止到2017-3-23 20:20:33开发结束)体验地址: http://pan.baidu.com/s/1bX28H4 新增传输列表 ======== ...
- 程序运行在.Net 4.0低版本上 报“System.NullReferenceException”错误
因为程序仅在个别机器上出现“ System.NullReferenceException”问题,而在其他机器上一切运行正常,所以认为是环境问题 具体错误信息如下: 2018-09-14 10:12:1 ...
- SNF开发平台WinForm-EasyQuery统计分析-效果-非常牛逼的报表查询工具
无论是单轴曲线 .双轴曲线 .柱形图 .饼图 .雷达图 .仪表图.图表引擎全能为您轻松实现.您只需要 3 步操作(数据源准备,设计图表,挂接到您想要展示的位置)便可完成 BI 的设计. 无论是普通报表 ...
- 西山居首页jQuery焦点图代码
西山居首页jQuery焦点图代码是一款带文字描述,左右箭头,索引按钮,自动轮播切换的jQuery特效代码.效果图如下: 在线预览 源码下载 实现的代码. html代码: <div style ...
- 在Ubuntu主机下实现与Windows虚拟机共享文件夹
一.概述 由于要实现Ubuntu主机中的一些文件与Windows虚拟机共享,因此要创建一个共享文件夹映射到虚拟机中. 网上许多都是Windows主机+Linux虚拟机的配置,在此分享主机是Linux的 ...
- ImportError: No module named 'requests.packages.urllib3'
场景:CentOS 7 运行微信告警脚本报错 原因:requests库版本问题 解决方法: sudo pip install requests urllib3 pyOpenSSL --force -- ...
- react服务端渲染同构报错Browser history needs a DOM
https://github.com/nozzle/react-static/issues/343 去掉了browserRouter就不报错了,但是又会有其他报错..
- MXPlayer ac3音轨支持问题
下载的MXPlayer 在播放kvm视频的时候没有声音, 说是不支持ac3的音频 到官网下载单独的解码包: https://mxplayerdownloads.com/mx-player-ac3-dt ...
- flex布局应用与踩坑
一.预告 本文不是一篇入门的文章所有请符合以下条件的战斗人员绕道: 1.初学前端,对前端的传统布局还不是很熟悉的人 2.后端人员对前端不打算深入学习的同学 二.开篇 flex布局原本是好几个月前就一直 ...
- maridb 10.3 主从复制,待机情况下从库 cpu 占用率高的处理方法
发现两台从库,一直都在CPU 占用率 60% 90% 中浮动, 但是写库却很正常.搜了一大把没找到答案,把参数测试了一下得出以下结论 slave my.cnf 添加如下参数 #只读模式 read_o ...