Skip to content

Commit

Permalink
Replace EmbeddedValue#set with EmbeddedValue#coerce
Browse files Browse the repository at this point in the history
  * this change is required so that it works correctly with collection
    member coercions
  • Loading branch information
solnic committed Feb 5, 2012
1 parent c8bb969 commit 42d1cf5
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 82 deletions.
15 changes: 5 additions & 10 deletions lib/virtus/attribute/embedded_value.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,26 +48,21 @@ def initialize(name, options = {})
@model = options.fetch(:model, OpenStruct)
end

# Set an embedded instance
# Coerce attributes into a virtus object
#
# @example
# address_attributes = { :street => 'Foo 1/2' }
# address = Address.new(address_attributes)
#
# attribute.set(instance, address)
# attribute.set(instance, address_attributes)
# @param [Hash,Virtus]
#
# @return [Virtus]
#
# @api public
def set(instance, attributes_or_object)
# @api private
def coerce(attributes_or_object)
value = if attributes_or_object.kind_of?(::Hash)
@model.new(attributes_or_object)
else
attributes_or_object
end

super(instance, value)
super(value)
end

end # class EmbeddedValue
Expand Down
50 changes: 50 additions & 0 deletions spec/unit/virtus/attribute/embedded_value/coerce_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
require 'spec_helper'

describe Virtus::Attribute::EmbeddedValue, '#coerce' do
subject { object.coerce(value) }

let(:attribute_name) { :attribute_name }
let(:model) { OpenStruct }
let(:instance) { Object.new }

context 'when the value is a hash' do
let(:value) { Hash[:foo => 'bar'] }

context 'when the options include the model' do
let(:object) { described_class.new(attribute_name, :model => model) }
let(:model) { mock('model') }
let(:model_instance) { mock('model_instance') }

before do
model.should_receive(:new).with(value).and_return(model_instance)
end

it { should be(model_instance) }
end

context 'with the default OpenStruct model' do
let(:model_instance) { OpenStruct.new(value) }

context 'when the options are an empty Hash' do
let(:object) { described_class.new(attribute_name, {}) }

it { should == model_instance }
end

context 'when the options are not provided' do
let(:object) { described_class.new(attribute_name) }

it { should == model_instance }
end
end
end

context 'when the value is not a hash' do
let(:object) { described_class.new(attribute_name) }
let(:value) { mock('value') }

before { model.should_not_receive(:new) }

it { should be(value) }
end
end
72 changes: 0 additions & 72 deletions spec/unit/virtus/attribute/embedded_value/set_spec.rb

This file was deleted.

0 comments on commit 42d1cf5

Please sign in to comment.