2015-05-04 86 views
0

我希望能夠使用通用代碼從不同模型擴展多個關聯,例如從extending_relation_method類方法。但是我不能在這個方法裏面實現self作爲關係對象。有什麼建議麼?謝謝。使用常用方法擴展多個模型的關聯

module ModelMixin 
    extend ActiveSupport::Concern 

    module ClassMethods 
    def extending_relation_method 
     owner = proxy_association.owner 
     # some processing 
     self 
    end 
    end 
end 

class Model < ActiveRecord::Base 
    include ModelMixin 

    def self.test1 
    self 
    end 

    has_many :field_values, as: :owner, autosave: true do 
    # works 
    define_method :test1 do 
     self 
    end 

    # works 
    def test2 
     self 
    end 

    # do not work 
    define_method :test3, &(Model.method(:extending_relation_method).unbind.bind(self)) 
    define_method :test4, &(Model.method(:extending_relation_method).unbind.bind(Model)) 
    end 
end 

UPDATE:

現在我認爲問題可以簡化爲找出原因和解決方法針對此行爲:

proc1 = Proc.new { self } 

def method_for_proc(*args) 
    self 
end 
proc2 = method(:method_for_proc).to_proc 

1.instance_exec(&proc1) 
#=> 1 
# as expected 

1.instance_exec(&proc2) 
#=> main 
# why?? 

解決原來的問題,通過更換共享的方法共享Proc,但我想明白爲什麼會發生這種情況。

module ModelMixin 
    EXTENDING_RELATION_PROC = Proc.new do 
    owner = proxy_association.owner 
    # some processing 
    self 
    end 
end 

class Model < ActiveRecord::Base 

    has_many :field_values, as: :owner, autosave: true do 
    # works 
    define_method :test, &EXTENDING_RELATION_PROC 
    end 
end 

回答

1

要使用特效調查您的問題,您可以看到在這裏http://ruby-doc.org/core-2.2.0/Method.html#method-i-to_procto_proc方法的源代碼註釋。所以to_proc創建新的Proc不與方法的主體,但與此方法的調用(在這種情況下限於main)。

但我認爲在您的特定情況下,它會更好寫類似:

module ModuleMixin 
    def extending_relation_method 
    # some processing 
    self 
    end 
end 

class Model < ActiveRecord::Base 
    has_many :field_values, as: :owner, autosave: true do 
    include ModuleMixin 
    end 
end