如何在 ruby 中做 attr_accessor_with_default? [英] How to do attr_accessor_with_default in ruby?
问题描述
我在 Rails 模型中使用 attr_accessor_with_default
的一些代码现在给我一个弃用警告,告诉我改用 Ruby!"
所以,我认为 ruby 1.9.2
中可能有一个新的部分使 attr_accessor
处理默认值,我用谷歌搜索了它,但我没有看到.我确实看到了一堆方法来覆盖 attr_accessor
来处理默认值.
当他们告诉我使用 Ruby"时,这就是他们的意思吗?或者我现在应该写完整的 getter/setter 吗?还是有什么新方法我找不到?
attr_accessor :pancakesdef after_initialize除非 new_record 返回?self.pancakes = 11结尾
<块引用>
这确保该值仅针对新记录初始化为某个默认值.
Some code that I had that used attr_accessor_with_default
in a rails model is now giving me a deprecation warning, telling me to "Use Ruby instead!"
So, thinking that maybe there was a new bit in ruby 1.9.2
that made attr_accessor
handle defaults, I googled it, but I don't see that. I did see a bunch of methods to override attr_accessor
to handle defaults though.
Is that what they mean when they tell me to "Use Ruby?" Or am I supposed to write full getters/setters now? Or is there some new way I can't find?
attr_accessor :pancakes
def after_initialize
return unless new_record?
self.pancakes = 11
end
This ensures that the value is initialized to some default for new record only.
这篇关于如何在 ruby 中做 attr_accessor_with_default?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!