2010-01-12 57 views
1

我有一個問題,使用acts_as_textiled和has_foreign_language插件在一起。在rails模型中擴展現有的屬性獲取器

的TextElement我在我的應用程序模型

class TextElement < ActiveRecord::Base 
    has_foreign_language :value 
    acts_as_textiled :value 

HasForeignLanguage

def has_foreign_language(*args) 
    args.each do |field| 
     # Define the Getter 
     define_method(field.to_s) do 
     . 
     . 
     . 

ActsAsTextiled

def acts_as_textiled(*attributes) 
. 
. 
. 
    attributes.each do |attribute| 
    define_method(attribute) do |*type| 
. 
. 
. 

這兩個插件都使用define_method,以及哪種方式我在TextElement中調用mixin,後者覆蓋之前定義的getter。

有沒有辦法保存現有的getter並在新定義的getter中調用它?類似於使用超級如果他們被遺傳。

我已經分出了這些插件,所以這裏都是公平的遊戲。

所有幫助表示讚賞。

回答

1

或者,您可以使用alias_method_chain重寫這兩個。

def some_class_method_that_overrides(*columns) 
    columns.each do | c | 
    overriden_name = if instance_methods.include?(c) 
     alias_method_chain(c.to_sym, "extra") 
     "#{c}_with_extra" 
    else 
     c 
    end 
    define_method(overriden_name) do ... 
    end 
    end 
end 
+0

你知道這裏發生了什麼嗎? alias_method_chain的文檔非常混亂。 –

+0

請谷歌爲alias_method_chain,它有什麼解釋負載 – Julik

0

你可以嘗試讓其中一個插件修飾屬性而不是重新定義它們。喜歡的東西(我在這裏延伸對象,但你可以擴展任何需要它):

class Object 
    def decorate!(attr) 
    method = self.method(attr) 
    define_method(attr) do |value| 
     result = method.call(value) 
     yield(result) 
    end 
    end 
end 
與裝飾

所以!你可以試試這個在acts_as_textilized

def acts_as_textiled(*attributes) 
. 
    attributes.each do |attribute| 
    self.decorate!(attribute) do |return_value_of_decorated_method| 
    # decorate code here 

或沿着這些線。未經測試,您可能需要調整,但基本想法在我的想法。

+0

謝謝戴夫我明天會告訴你,如果它能完成這項工作,請告訴你。 –