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