Re: [連結] ActiveRecord act_as_xxx的原理跟template

看板Ruby作者 (godfat 真常)時間17年前 (2007/11/03 02:05), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《ddman (ddman)》之銘言: : 覺得act_as_xxx很神奇,去找了一下,有兩篇文章講原理跟一個簡單的template : 原理: http://tinyurl.com/275usq : template: http://textsnippets.com/posts/show/384 : 基本上是利用mixing來做。我得承認以我的程度,不是很瞭解...Orz : 有高手可以幫忙解釋一下? 是不是想得太複雜了?我承認我沒仔細看,(只翻了一下 code, 文章沒看) 也跟 rails 不熟 XDDD 不過看起來大致上就是很單純的 mixing. (只是繞了非常多圈,所以也許 ruby 不夠熟可能會覺得混亂) ActiveRecord::Base.send(:include, MyMod::Acts::Roled) 叫 ActiveRecord::Base 去 include MyMod::Acts::Roled 這個動作,會觸發: def self.included(base) # Add acts_as_roled availability by extending the module # that owns the function. base.extend AddActsAsMethod end 這是 ruby 本身的機制,當 module 被 included 時會呼叫的 hook, base 就是那個 mixer, 這裡就會是:ActiveRecord::Base, 因為是他去 include Roled 於是就等同於呼叫 ActiveRecord::Base.extend AddActsAsMethod 所以 ActiveRecord::Base 就獲得了:acts_as_random 這個 method, 接下來就可以這樣: class MyModel < ActiveRecord::Base act_as_random end 因為 MyModel 繼承 Base, 所以當然能用 Base 的 method acts_as_random 於是 MyModel 就會執行這段: class_eval <<-END include MyMod::Acts::Roled::InstanceMethods END 這簡單地說就是很正常的 include, 所以 InstanceMethods 這個 module 就會被 include 到 MyModel 中,於是理所當然 MyModel 就能使用 這些 instance methods. 同時這段也會被執行到: def self.included(aClass) aClass.extend ClassMethods end aClass 就會是 MyModel, 因為是他去 include InstanceMethods, 然後他又被 extend ClassMethods, 所以 MyModel 也會獲得這些 class methods. 以上只是隨意的解釋,也沒細看該網站上的文章,所以如果有誤望請指正 :) 不過我想應該沒什麼錯,因為我之前有稍微翻過 rails plugin 的作法, 有參考過一些 plugin 的大致作法,跟上面那樣做還滿像的。 不過老實講,我個人覺得這樣做還蠻多此一舉的,繞了太多圈了,很麻煩。 除非需要做到很大的 plugin 吧?否則我覺得就一個 module 就好了。 頂多這樣吧? module ClassMethods def class_method; 'class_method'; end end module InstanceMethods def instance_method; 'instance_method'; end; end class MyModel < ActiveRecord::Base include InstanceMethods extend ClassMethods end 嫌要 include 又要 extend 很麻煩的話: module MyPlugin def self.included base base.__send__ :include, InstanceMethods base.__send__ :extend, ClassMethods # 因為這些是 private methods end end 然後 class MyModel < ActiveRecord::Base include MyPlugin end 這樣就好了,省得繞那麼多圈看得暈頭轉向的。 如果還是喜歡 act_as_... 的名字: def ActiveRecord::Base.act_as_me include MyPlugin end 就可以: class MyModel < ActiveRecord::Base act_as_me end 試試吧,我剛剛試了一下沒什麼問題。 在 rails 中的話要考慮各 .rb 的執行順序即可。 -- In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. 《Programming Bottom-Up》- Paul Graham 1993 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.28.18

11/03 21:57, , 1F
我沒深入研究ruby mixing,module跟繼承,得花時間看看
11/03 21:57, 1F

11/04 09:23, , 2F
看 Programming Ruby 24 章:Classes and Objects 即可
11/04 09:23, 2F
文章代碼(AID): #17AsRhVl (Ruby)
文章代碼(AID): #17AsRhVl (Ruby)