1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
require 'virtus'
describe 'Injectible coercer' do
before do
module Examples
class EmailAddress
include Virtus.value_object
values do
attribute :address, String, :coercer => lambda { |add| add.downcase }
end
def self.coerce(input)
if input.is_a?(String)
new(:address => input)
else
new(input)
end
end
end
class User
include Virtus.model
attribute :email, EmailAddress,
:coercer => lambda { |input| Examples::EmailAddress.coerce(input) }
end
end
end
after do
Examples.send(:remove_const, :EmailAddress)
Examples.send(:remove_const, :User)
end
let(:doe) { Examples::EmailAddress.new(:address => 'john.doe@example.com') }
it 'accepts an email hash' do
user = Examples::User.new :email => { :address => 'John.Doe@Example.Com' }
expect(user.email).to eq(doe)
end
it 'coerces an embedded string' do
user = Examples::User.new :email => 'John.Doe@Example.Com'
expect(user.email).to eq(doe)
end
end
|