2007-06-14

最近的Ruby for Rails读书笔记

关键字: dynamic ruby
1, 用"class <<"定义class method
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
评论
发表评论

您还没有登录,请登录后发表评论

hideto
搜索本博客
我的相册
A6bdc31c-c66e-468e-961e-9cc721e82adc-thumb
screenshot
共 1 张
存档
最新评论