是否可以使用 Object.new(:attribute => "foobar") 和 attr_accessors 创建对象?

发布于 2024-10-15 05:41:46 字数 519 浏览 2 评论 0 原文

我似乎无法解决这个问题。

我想在没有数据库的情况下完成此操作:

Object.new(:attribute_1 => "foobar", :attribute_2 => "foobar")

返回此:

ArgumentError: wrong number of arguments (1 for 0)
    from (irb):5:in `initialize'
    from (irb):5:in `new'
    from (irb):5

我的模型:

class Object
  extend ActiveModel::Naming
  include ActiveModel::Conversion

  def persisted?
    false
  end

  attr_accessor :attribute_1, :attribute_2

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

日裸衫吸 2024-10-22 05:41:46

我假设您并没有真正使用 Object 作为类名。如果是这种情况,您只需添加逻辑来在构造函数中设置属性:

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)

输出:

#<Foo:0x2ac3d3a890a0>
#<Foo:0x2ac3d3a88e20 @baz=123, @bar="abc">

请注意,在现实生活中,您需要检查构造函数中传递的属性列表,以确保它们是您的有效属性。班级。

I'm going to assume that you aren't really using Object as your class name. 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.

花开雨落又逢春i 2024-10-22 05:41:46

您可以重写initialize方法来更改Object.new的行为:

class Object
  def initialize( arguments )
    # Do something with arguments here
  end
end

You can override the initialize method to change the behavior of Object.new:

class Object
  def initialize( arguments )
    # Do something with arguments here
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文