aTTOMER(:aTTible =>“ Foobar”)を使用してobject.newを使用してオブジェクトを作成することは可能ですか?

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

  •  27-10-2019
  •  | 
  •  

質問

私はこれを解決できないようです。

データベースなしでこれを達成したい:

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
役に立ちましたか?

解決

私はあなたが実際に使用していないと仮定するつもりです 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">

実際の生活では、コンストラクターに渡された属性のリストをチェックして、それらがクラスの有効な属性であることを確認することをお勧めします。

他のヒント

初期化メソッドをオーバーライドして、オブジェクトの動作を変更できます。

class Object
  def initialize( arguments )
    # Do something with arguments here
  end
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top