I have an object Foo
and want to assign multiple attributes to it at once, similar to assign_attributes
in Rails:
class Foo
attr_accessor :a, :b, :c
end
f = Foo.new
my_hash = {a: "foo", b: "bar", c: "baz"}
f.assign_attributes(my_hash)
The above does not work except if the class is an ActiveRecord Model in Rails. Is there any way to do it in Ruby?
CodePudding user response:
You can implement the mass-assignment method yourself.
One option is to set the corresponding instance variables via instance_variable_set
:
class Foo
attr_accessor :a, :b, :c
def assign_attributes(attrs)
attrs.each_pair do |attr, value|
instance_variable_set("@#{attr}", value)
end
end
end
another way is to dynamically invoke the setters via public_send
:
def assign_attributes(attrs)
attrs.each_pair do |attr, value|
public_send("#{attr}=", value)
end
end
In addition, you might want to ensure that the passed argument is a hash and that its keys are valid / known attributes.
Using the latter approach conveys an advantage, in that if a setter has been defined to include constraints and controls on the value being set, the latter approach respects that.
CodePudding user response:
The assign_attributes
is an instance method of ActiveRecord
You have to define your assign_attributes
method if not using ActiveRecord
def assign_attributes(attrs_hash)
attrs_hash.each do |k, v|
self.instance_variable_set("@#{k}", v)
end
end