3

许多 gem 使用如下代码覆盖 Rails 的属性访问器:

define_method "#{dynamic_name}" do
  value = read_attribute(dynamic_name)
  # Do stuff
end

或这个:

belongs_to :user
def user
  # Do stuff
end

Rails 4.2 为属性方法引入了缓存(AttributeMethodCache, ReaderMethodCache, https://github.com/rails/rails/pull/15429

当使用上述方法访问被覆盖的属性时,这会导致错误的值。看起来原始读取器方法的返回值即使在覆盖该方法后也被缓存并返回。

在 Rails 4.2 中覆盖属性访问器的推荐过程是什么?

4

0 回答 0