如何初始化“attr_accessor中”属性值? [英] How to initialize 'attr_accessor' attribute values?

查看:655
本文介绍了如何初始化“attr_accessor中”属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
   attr_accessor中的默认值

我on Rails的3.0.9使用Ruby,我想初始化一些 attr_accessor中中从 ActiveRecord的继承我的类\\型号属性值:: Base的。即,

I am using Ruby on Rails 3.0.9 and I would like to initialize some attr_accessor attribute values in my class\model that inherits from ActiveRecord::Base. That is,

...我的模块中我有:

... in my module I have:

class User < ActiveRecord::Base
  attr_accessor :attribute_name1,
                :attribute_name2,
                :attribute_name3,
                ...
end

我想设置为真正所有 attr_accessor中属性值的。 我怎么能这样做?

P.S:的我当然想解决逼近点菜Ruby on Rails的路上面的问题。我知道关于 after_initialize 回调,但使用这种方法,我应该重复每个 ATTRIBUTE_NAME&LT; N&GT; 语句,我会喜欢将值设置为真正 after_initialize 语句(...和这里面是的干 - 不要重复自己)。也许有更好的方式来实现这一目标。的有没有一种方法来设置 attr_accessor中当你说出这些属性对飞属性值?也就是说,我希望宣布和设置 attr_accessor中属性一次!

P.S.: Of course I would like to solve the above issue approaching "à la Ruby on Rails Way". I know about the after_initialize callback but by using that method I should repeat each attribute_name<N> statement for which I would like to set the value to true inside that after_initialize statement (... and this is not DRY - Don't Repeat Yourself). Maybe there is a better way to achieve this. Is there a way to set attr_accessor attribute values "on the fly" when you state those attributes? That is, I expect to declare and set attr_accessor attributes at once!

推荐答案

有关的Rails 3.2或更早版本,你可以使用的 attr_accessor_with_default

For Rails 3.2 or earlier, you could use attr_accessor_with_default:

class User < ActiveRecord::Base
  attr_accessor_with_default :attribute_name1, true
  attr_accessor_with_default :attribute_name2, true
  attr_accessor_with_default :attribute_name3, true
  ...
end

由于您的默认值是一个不可变的类型(布尔),这种形式的方法是安全的,在这里使用。但是,如果默认值是一个可变对象,包括数组或字符串不使用它,因为所有新的模型对象将共享完全相同的情况下,这可能不是你想要的。

Since your default value is an immutable type (boolean), this form of the method is safe to use here. But don't use it if the default value is a mutable object, including an array or string, because all of your new model objects will share the exact same instance, which is probably not what you want.

相反, attr_accessor_with_default 将接受块,在那里你可以每次都返回一个新的实例:

Instead, attr_accessor_with_default will accept a block, where you can return a new instance each time:

attr_accessor_with_default(:attribute_name) { FizzBuzz.new }

这篇关于如何初始化“attr_accessor中”属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆