[英]alias_attribute and creating and method with the original attribute name causes a loop
Im trying to dynamically create a method chain in one attribute in my model. 我试图在模型的一个属性中动态创建方法链。 By now I have this function:
现在我有了这个功能:
def create_filtered_attribute(attribute_name)
alias_attribute "#{attribute_name}_without_filter", attribute_name
define_method "#{attribute_name}" do
filter_words(self.send("#{attribute_name}_without_filter"))
end
end
so I receive a string with the attribute name, alias it for ' _without_filter ' (alias_method or alias_method_chain fails here, because the attribute isnt there when the class is created), and I create a new method with the attribute name, where I filter its contents. 因此,我收到一个带有属性名称的字符串,为' _without_filter '别名(alias_method或alias_method_chain在此处失败,因为创建类时该属性不存在),并且我创建了一个带有属性名称的新方法,并对其进行过滤内容。
But somehow, when I call "#{attribute_name}_without_filter" it calls my new method (i think because the alias_attribute some how), and the program goes into a stack loop. 但是以某种方式,当我调用“#{attribute_name} _without_filter”时,它将调用我的新方法(我认为是因为alias_attribute的方式如何),然后程序进入了堆栈循环。
Im trying to rename that attribute, so I can use its name for a method... 我正在尝试重命名该属性,因此我可以将其名称用于方法...
Can someone please enlighten me on this. 有人可以给我启发。
There is a difference between alias_method
and alias_attribute
. alias_method
和alias_attribute
之间有区别。 alias_method actually makes a copy of the old method, whereas alias_attribute just defines new methods, which call old ones . alias_method实际上是旧方法的副本 ,而alias_attribute只是定义了新方法,它们调用了旧方法 。
Note, that model.attribute
and model.attribute=
methods in ActiveRecord simply call read_attribute and write_attribute , so you always can access your attribute, even if you override it's getter or setter: 请注意,
model.attribute
和model.attribute=
在ActiveRecord的方法简单地调用read_attribute和write_attribute ,让你随时可以访问自己的属性,即使你忽略它的getter或setter:
define_method "#{attribute_name}" do
filter_words(self.read_attribute(attribute_name))
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.