Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding recursive #to_hash implementation and spec. #83

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/virtus/instance_methods.rb
Expand Up @@ -112,7 +112,8 @@ def attributes=(attributes)
set_attributes(attributes)
end

# Returns a hash of all publicly accessible attributes
# Returns a hash of all publicly accessible attributes by
# recursively calling #to_hash on the objects that respond to it.
#
# @example
# class User
Expand All @@ -129,7 +130,13 @@ def attributes=(attributes)
#
# @api public
def to_hash
attributes
attrs = attributes.dup
attrs.each do |key, value|
if value.respond_to?(:to_hash)
hash[key] = value.to_hash
end
end
attrs
end

private
Expand Down
26 changes: 19 additions & 7 deletions spec/unit/virtus/instance_methods/to_hash_spec.rb
Expand Up @@ -3,17 +3,29 @@
describe Virtus::InstanceMethods, '#to_hash' do
subject { object.to_hash }

class Model
class Address
include Virtus

attribute :name, String
attribute :age, Integer
attribute :email, String, :accessor => :private
attribute :street, String
attribute :city, String
end

let(:model) { Model }
let(:object) { model.new(attributes) }
let(:attributes) { { :name => 'john', :age => 28 } }
class Person
include Virtus

attribute :name, String
attribute :age, Integer
attribute :email, String, :accessor => :private
attribute :address, Address
end

let(:model) { Person }
let(:child_record) { Address }

let(:address) { { :street => "Sunshinestr.", :city => "Berlin" } }
let(:object) { model.new(attributes) }

let(:attributes) { { :name => 'john', :age => 28, :address => child_record } }

it { should be_instance_of(Hash) }

Expand Down