简体   繁体   English

是否可以使用带有attr_accessors的Object.new(:attribute =>“ foobar”)创建对象?

[英]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.

相关问题 将对象转换为JSON时看不到attr_accessors - Unable to see attr_accessors when transforming object to JSON 使用 Rails 对象的属性在 ruby​​ 中批量分配 attr_accessors 的最佳方法 - Best way to mass assign attr_accessors in ruby with the attributes of a Rails object attr_accessors只是属性更改的触发器回调吗? - attr_accessors are only attribute changed trigger callbacks? 从object.new删​​除临时对象? - Delete the temporary object from object.new? 检查忽略Object.new的最后保存的项目 - Check for last saved item that ignores Object.new 如何在Controller中将附加属性或参数传递给Object.new - How to pass addition attributes or arguments to a Object.new in Controller 使用外键创建Object.New会导致无效? - Creating a Object.New with a foreign key results in nil? 创建对象然后重定向到该对象路径会导致每次刷新页面时连续运行Object.new - Creating an object then redirecting to that objects path results in continuously running Object.new everytime the page is refreshed 如何创建引用现有嵌套属性的新对象? - How do I create a new object referencing an existing nested attribute? 如何保存对象的值属性,查看创建具有相同值的新对象 - How to pass value attribute of an object was saved, to view to create new object has that same value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM