solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 228 forks source link

Thoughts on #nested_hash #289

Closed techthumb closed 1 year ago

techthumb commented 9 years ago

Hi,

We have a need for comparing the hash representation of a Virtus.model for testing purposes.

Currently #to_hash is aliased to #attributes.

However #attributes doesn't return the hash representation of models that are embedded or models that are part of a collection.

We are considering working around the situation by introducing a #nested_hash method. The (untested) code looks like:

Virtus::InstanceMethods::MassAssignment.module_eval do
  def nested_hash
    copy_of_attributes = attributes.deep_dup
    copy_of_attributes.each do | key, value |
      copy_of_attributes[key] = value.nested_hash if value.class.included_modules.include?(Virtus::Model::Core)
      if value.is_a?(Array)
        copy_of_attributes[key] = value.map do | item |
          item.class.included_modules.include?(Virtus::Model::Core) ? item.nested_hash : item
        end
      end
    end
    copy_of_attributes
  end
end

What are your thoughts on making #to_hash recursive or adding a new method like #nested_hash to support the requirement?

/cc @russvanbert @dueckes

solnic commented 9 years ago

Please take a look at my comment in #290.

I can already start a 2.0 branch and extract this stuff to a separate gem although I'm not interested in maintaining it so help will be highly appreciated :)