2008年10月29日 星期三

module_eval,class_eval,singleton

http://onestepback.org/articles/10things/page027.html
http://my.donews.com/idlecat/2006/08/20/IpzenftEYkWGFjJpxPTDTJTCDOGKqTPzCaPZ/llllll
http://blackanger.blog.51cto.com/140924/84057
http://fcamel.twbbs.org/archives/2008/04/07/474/
http://tw.myblog.yahoo.com/weijenlu/article?mid=99&prev=109&next=-1

class Module
def trace_attr(sym)
self.module_eval <<-EOS <= 也可以說是動態產生 method 的方法
def #{sym}
printf "Accessing %s with value %s\n",
"#{sym}", @#{sym}.inspect
@#{sym}

end
EOS
end
end

class Dog
trace_attr :name
def initialize(string)
@name = string
end
end
p Dog.new("Fido").name


class Test
end

code =<<-EOF
def hello_module
'hello world, use module'
end
EOF Test.module_eval(code) <= 動態塞段 code 進去, method 就生了, 太神啦
p Test.new.hello_module()


Test.class_eval <<-END <= 有直接塞進class的 fu
def hello_class
' hello world, use class'
end
END
p Test.new.hello_class()

t = Test.new
class << t <= 可以直接塞method 進 t 這個 object
def hello_singleton
'hello singleton'
end
end

class << Test <= Test class也是 oject 當然也可以塞
def class_singleton
'class singleton'
end
end



class Announce < ActiveRecord::Base
require_dependency 'forum/forum_model_mixin'
include ForumModelMixin
end

module ForumModelMixin
def self.included(klass) <= klass可以知道是哪個 class include了這個lib
klass.class_eval do

has_many :forum_comments, :as => :forum
alias_method :old_destroy, :destroy
validates_presence_of :content, :subject, :user_id

def destroy(r)
if r
old_destroy
else
update_attribute(:removed_at, Time.now) if !removed_at
end
end
end
end
end

沒有留言: