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

1.2k views Asked by At

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
2

There are 2 answers

0
cam On BEST ANSWER

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.

0
drummondj On

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