gpt4 book ai didi

ruby-on-rails - 如何在运行时扩展从 ActiveRecord 关联返回的对象?

转载 作者:数据小太阳 更新时间:2023-10-29 07:40:02 25 4
gpt4 key购买 nike

我有一个模型如下:

class Property < ActiveRecord::Base
has_and_belongs_to_many :property_values
end

我想做的是使用由 Property 对象的属性确定的模块来扩展 property_values 扩展上的查找返回的任何值。我试过这样的事情:

class Property < ActiveRecord::Base
has_and_belongs_to_many :property_values, :extend => PropertyUtil::Extensible

def enrich(to_extend)
modules.split(/\s*,\s*/).each do |mod|
to_extend.extend(Properties.const_get(mod.to_sym))
end
end
end

module PropertyUtil
module Extensible
def self.extended(mod)
mod.module_eval do
alias old_find find
end
end

def find(*args)
old_find(*args).map{|prop| proxy_owner.enrich(prop)}
end
end
end

所有可能被选中的模块都在属性模块中定义。但是,在尝试使用此代码运行时,存在一些问题;首先,令我惊讶的是,没有一个动态查找器(property_values.find_by_name 等)似乎委托(delegate)查找;其次,当我尝试直接运行查找时,我如何完成别名会导致堆栈溢出。

有没有办法做我正在尝试的事情?我可以对什么方法进行别名和覆盖,以便关联扩展返回的所有结果,无论它们是如何检索的,都使用适当的模块进行扩展?

谢谢,克里斯

最佳答案

我从未尝试这样做,但您可能想尝试以下操作(我只是更改了别名的完成方式):

class Property < ActiveRecord::Base
has_and_belongs_to_many :property_values, :extend => PropertyUtil::Extensible

def enrich(to_extend)
modules.split(/\s*,\s*/).each do |mod|
to_extend.extend(Properties.const_get(mod.to_sym))
end
end
end

module PropertyUtil
module Extensible
def self.extended(mod)
mod.module_eval do
alias_method :old_find, :find
alias_method :find, :new_find
end
end

def new_find(*args)
old_find(*args).map{|prop| proxy_owner.enrich(prop)}
end
end
end

如果它在这里不起作用是您可能想尝试的另一个想法:

class Value < ActiveRecord::Base
self.abstract_class = true

end


class ExtendedValue < Value

end

class ExtendedValue2 < Value

end


class Property < ActiveRecord::Base
has_and_belongs_to_many :property_values, :class_name => 'ExtendedValue'
has_and_belongs_to_many :property_values_extended, :class_name => 'ExtendedValue'
has_and_belongs_to_many :property_values_extended2, :class_name => 'ExtendedValue2'


end

这个想法是为每个“类型”建立一个 hatbm 关联(如果你可以那样对你的扩展进行分组)并在给定时间使用你想要的那个,如果你可以那样做你想做的事我也很确定与在 activerecord 返回它们之后修补每个返回的对象相比,它对性能的影响更小。

我有点好奇你想用这个实现什么:)

关于ruby-on-rails - 如何在运行时扩展从 ActiveRecord 关联返回的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4363981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com