Best way to mass assign attr_accessors in ruby with the attributes of a Rails object

By : Jwan622

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:


Say the PORO is called API::Apple

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

By : Jwan622


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.

You should strive to split your application into modules according to your features.

  • Angular modules make it easier to isolate,test and re-use features.
  • Angular modules make it easy to lazy load routable features.

If we would stick with Angular tutorial example: It will make sense to group all heroes under HeroesModule and the villains under VillainsModule. Secondly, if you have Common functionality that is related to both of them and other modules in your app , you can create another module e.g. CommonModule.

For instance, Angular 2 itself ships with Common module that provides basic functionality such as NgFor and NgIf directives.

By : Omri L

Use Integer.parseInt, and Character.toString as @NeilLocketz mentioned. Your array A is an array of int, so you need to get the underlying integer values of the characters you are reading.

for (int i = A.length - 1; j >= 0 && i >= 0; --i){
    A[i] = Integer.parseInt(Character.toString(s.charAt(j)));

This video can help you solving your question :)
By: admin