我希望能够使用公共代码从不同的模型扩展多个关联,例如从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更新:
现在,我认为问题可以简化为找出这种行为的原因和解决办法:
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发布于 2015-05-04 13:41:15
要研究procs的问题,您可以在to_proc方法的源代码中看到注释,这里是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
endhttps://stackoverflow.com/questions/30028278
复制相似问题