hideto 发表于 2013-1-27 06:04:22

最近的Ruby for Rails读书笔记

1, 用"class <<"定义class method
class User < ActiveRecord::Baseclass << selfdef authenticate(username, password)    find_by_username(username, :conditions => )end

2, 用self.included(class)方法作为include模块的hooks
module Mdef self.included(c)    puts "I have just been mixed into #{c}."endendclass Cinclude Mend

3, 用self.inherited(subclass)作为class继承的hooks
class Cdef self.inherited(subclass)    puts "#{self} just got subclassed by #{subclass}"endendclass D < Cend
用self.const_missing(const)作为class缺失const的hooks
class Cdef self.const_missing(const)    puts "#{const} is undefined-setting it to 1."    const_set(const, 1)endendputs 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
页: [1]
查看完整版本: 最近的Ruby for Rails读书笔记