开发者

Is it possible to create an object using Object.new(:attribute => "foobar") with attr_accessors?

开发者 https://www.devze.com 2023-02-07 03:10 出处:网络
I can\'t seem to resolve this. I want to accomplish this without a database : Object.new(:attribute_1开发者_Go百科 => \"foobar\", :attribute_2 => \"foobar\")

I can't seem to resolve this.

I want to accomplish this without a database :

Object.new(:attribute_1开发者_Go百科 => "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. 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:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号