如何一次将多个属性分配给 Ruby 中的一个对象
How to assign multiple attributes at once to an object in Ruby
我有一个对象Foo
,想一次性给它分配多个属性,类似于Rails中的assign_attributes
:
class Foo
attr_accessor :a, :b, :c
end
f = Foo.new
my_hash = {a: "foo", b: "bar", c: "baz"}
f.assign_attributes(my_hash)
除非 class 是 Rails 中的 ActiveRecord 模型,否则上述方法不起作用。 Ruby有什么办法吗?
您可以自己实现批量分配方法。
一种选择是通过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
请注意,这将绕过任何自定义 setter。如文档中所述:
This may circumvent the encapsulation intended by the author of the class, so it should be used with care.
另一种方法是通过 public_send
:
动态调用 setters
def assign_attributes(attrs)
attrs.each_pair do |attr, value|
public_send("#{attr}=", value)
end
end
这相当于按顺序设置每个单独的属性。如果 setter 已被(重新)定义为包括对所设置值的约束和控制,则后一种方法会尊重这一点。
如果您尝试设置未定义的属性,它也会引发异常:(因为相应的 setter 不存在)
f = Foo.new
f.assign_attributes(d: 'qux')
#=> NoMehodError: undefined method `d=' for #<Foo:0x00007fbb76038430>
此外,您可能希望确保传递的参数确实是哈希值,并且如果提供的属性无效/未知,则可能会引发自定义异常。
assign_attributes
是ActiveRecord
的实例方法
如果不使用 ActiveRecord
,则必须定义 assign_attributes
方法
def assign_attributes(attrs_hash)
attrs_hash.each do |k, v|
self.instance_variable_set("@#{k}", v)
end
end
我有一个对象Foo
,想一次性给它分配多个属性,类似于Rails中的assign_attributes
:
class Foo
attr_accessor :a, :b, :c
end
f = Foo.new
my_hash = {a: "foo", b: "bar", c: "baz"}
f.assign_attributes(my_hash)
除非 class 是 Rails 中的 ActiveRecord 模型,否则上述方法不起作用。 Ruby有什么办法吗?
您可以自己实现批量分配方法。
一种选择是通过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
请注意,这将绕过任何自定义 setter。如文档中所述:
This may circumvent the encapsulation intended by the author of the class, so it should be used with care.
另一种方法是通过 public_send
:
def assign_attributes(attrs)
attrs.each_pair do |attr, value|
public_send("#{attr}=", value)
end
end
这相当于按顺序设置每个单独的属性。如果 setter 已被(重新)定义为包括对所设置值的约束和控制,则后一种方法会尊重这一点。
如果您尝试设置未定义的属性,它也会引发异常:(因为相应的 setter 不存在)
f = Foo.new
f.assign_attributes(d: 'qux')
#=> NoMehodError: undefined method `d=' for #<Foo:0x00007fbb76038430>
此外,您可能希望确保传递的参数确实是哈希值,并且如果提供的属性无效/未知,则可能会引发自定义异常。
assign_attributes
是ActiveRecord
如果不使用 ActiveRecord
assign_attributes
方法
def assign_attributes(attrs_hash)
attrs_hash.each do |k, v|
self.instance_variable_set("@#{k}", v)
end
end