E 'possibile creare un oggetto utilizzando Object.new (: attributo => “foobar”) con attr_accessors?

StackOverflow https://stackoverflow.com/questions/4833471

  •  27-10-2019
  •  | 
  •  

Domanda

Non riesco a risolvere questo.

che voglio realizzare questo senza un database:

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

Che ritorno questo:

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

il mio modello:

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

  def persisted?
    false
  end

  attr_accessor :attribute_1, :attribute_2
È stato utile?

Soluzione

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.

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top