Jwan622 Jwan622 - 10 months ago 46
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

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


Say the PORO is called

If I initialize an
, how can I mass assign all of its
s with the attributes of the database-backed
. Is there an easy way to do this? Does something like this exist?

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

Answer Source

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


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.