[英]Best way to mass assign attr_accessors in ruby with the attributes of a Rails object
In short, I want to mass assign a PORO with no database with like 100 attr_accessors with the attributes of a Rails object.简而言之,我想批量分配一个没有数据库的 PORO,其中有 100 个具有 Rails 对象属性的 attr_accessors。 The point of this is to expose an object over the API that is not an ActiveRecord Object and this API is being used internally right now and is not separated over a service.
这样做的目的是通过 API 公开一个对象,该对象不是 ActiveRecord 对象,并且这个 API 现在正在内部使用,并且没有通过服务分离。 What can be done?
可以做什么?
Assume we have a database-backed Database::Apple
class with attributes.假设我们有一个带有属性的数据库支持的
Database::Apple
类。 I can get them all in a hash using:我可以使用以下方法将它们全部放入哈希中:
Database::Apple.first.attributes
Say the PORO is called API::Apple
假设 PORO 被称为
API::Apple
If I initialize an API::Apple
, how can I mass assign all of its attr_accessor
s with the attributes of the database-backed Apple
.如果我初始化一个
API::Apple
,我怎么能用数据库支持的Apple
的属性批量分配它的所有attr_accessor
。 Is there an easy way to do this?是否有捷径可寻? Does something like this exist?
这样的东西存在吗?
Database::Apple.new.attributes = API::Apple.first.attributes
? Database::Apple.new.attributes = API::Apple.first.attributes
?
Something along these lines could do it for you.沿着这些方向的东西可以为你做。
class API::Apple < SimpleDelegator
# pass a `Database::Apple` instance to initializer
def initialize(database_apple)
@database_apple = database_apple
super
end
end
A concrete implementation of
Delegator
, this class provides the means to delegate all supported method calls to the object passed into the constructor.作为
Delegator
的具体实现,此类提供了将所有支持的方法调用委托给传递给构造函数的对象的方法。
So in other words any instance of your API::Apple
PORO will have access to all 100 attributes of the Database::Apple
instance.因此,换句话说,您的
API::Apple
PORO 的任何实例都可以访问Database::Apple
实例的所有 100 个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.