Jwan622 Jwan622 - 2 months ago 12
Ruby Question

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. 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. What can be done?

Assume we have a database-backed

Database::Apple
class with attributes. I can get them all in a hash using:

Database::Apple.first.attributes


Say the PORO is called
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
. Is there an easy way to do this? Does something like this exist?

Database::Apple.new.attributes = API::Apple.first.attributes
?

Answer

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

SimpleDelegator

A concrete implementation of Delegator, this class provides the means to delegate all supported method calls to the object passed into the constructor.

So in other words any instance of your API::Apple PORO will have access to all 100 attributes of the Database::Apple instance.

Comments