2007-06-14
最近的Ruby for Rails读书笔记
关键字: dynamic ruby
1, 用"class <<"定义class method
2, 用self.included(class)方法作为include模块的hooks
3, 用self.inherited(subclass)作为class继承的hooks
用self.const_missing(const)作为class缺失const的hooks
4, 用eval/instance_eval/class_eval(module_eval)动态执行程序
5, 用Proc定义代码块
6, 用lambda定义匿名方法
class User < ActiveRecord::Base
class << self
def authenticate(username, password)
find_by_username(username, :conditions => [password_hash = ?", Digest::SHA1.hexdigest(passwword)])
end
2, 用self.included(class)方法作为include模块的hooks
module M
def self.included(c)
puts "I have just been mixed into #{c}."
end
end
class C
include M
end
3, 用self.inherited(subclass)作为class继承的hooks
class C
def self.inherited(subclass)
puts "#{self} just got subclassed by #{subclass}"
end
end
class D < C
end
用self.const_missing(const)作为class缺失const的hooks
class C
def self.const_missing(const)
puts "#{const} is undefined-setting it to 1."
const_set(const, 1)
end
end
puts C::A
4, 用eval/instance_eval/class_eval(module_eval)动态执行程序
str = "hello" eval "str + ' Fred'"
5, 用Proc定义代码块
pr = Proc.new { |x| puts "Called with argument #{x}" }
6, 用lambda定义匿名方法
lam = lambda { puts "A lambda!" }
lam.call
发表评论
- 浏览: 681839 次
- 性别:

- 来自: BJ

- 详细资料
搜索本博客
我的相册
screenshot
共 1 张
共 1 张
最近加入圈子
最新评论
-
Mnesia用户手册:三,构建 ...
要想创建disc_copies和disc_only_copies类型的表有两个前 ...
-- by hideto -
翻译www.djangobook.com之 ...
有个问题问一下: 我先配置了一个urlpatterns是这样的: r'^myd ...
-- by lyhapple -
Why OO sucks
gigix 写道lyl0035 写道为啥就没人想想,其实在面向对象的代码中也流露 ...
-- by hurd -
Why OO sucks
貌似又回到当年java vs c的年代。两种方式,不管是OO还是FP,仅是人处理 ...
-- by python -
大家可以抛弃Java踹死Djan ...
to phoenixup:1,你还别说,你举的什么Struts,Tapestry ...
-- by hideto






评论排行榜