[英]Is it possible to create an object using Object.new(:attribute => “foobar”) with attr_accessors?
I can't seem to resolve this. 我似乎无法解决这个问题。
I want to accomplish this without a database : 我想在没有数据库的情况下完成此操作:
Object.new(:attribute_1 => "foobar", :attribute_2 => "foobar")
That return this : 那返回这个:
ArgumentError: wrong number of arguments (1 for 0)
from (irb):5:in `initialize'
from (irb):5:in `new'
from (irb):5
my model: 我的模特:
class Object
extend ActiveModel::Naming
include ActiveModel::Conversion
def persisted?
false
end
attr_accessor :attribute_1, :attribute_2
I'm going to assume that you aren't really using Object
as your class name. 我将假设您并没有真正使用
Object
作为类名。 If that is the case, you just need to add the logic to set your attributes in your constructor: 如果是这种情况,您只需要添加逻辑即可在构造函数中设置属性:
class Foo
attr_accessor :bar, :baz
def initialize(attrs = {})
attrs.each { |attr,val| instance_variable_set "@#{attr}", val }
end
end
p Foo.new
p Foo.new(:bar => "abc", :baz => 123)
outputs: 输出:
#<Foo:0x2ac3d3a890a0>
#<Foo:0x2ac3d3a88e20 @baz=123, @bar="abc">
Note that in real life you would want to check the list of attributes passed in the constructor to make sure they are valid attributes for your class. 请注意,在现实生活中,您将需要检查在构造函数中传递的属性列表,以确保它们是您类的有效属性。
You can override the initialize method to change the behavior of Object.new: 您可以重写initialize方法来更改Object.new的行为:
class Object
def initialize( arguments )
# Do something with arguments here
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.