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?
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 :)
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:What are your thoughts on making
#to_hash
recursive or adding a new method like#nested_hash
to support the requirement?/cc @russvanbert @dueckes