Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions spec/integration/custom_attributes_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@

before do
module Examples
class ExternalObjectId
attr_reader :oid
include Equalizer.new(:oid)
def initialize(oid)
@oid = oid
end

def self.from_string(oid)
new(oid)
end
end

class ExternalObjectIdAttribute < Virtus::Attribute
primitive ExternalObjectId

def coerce(input)
ExternalObjectId.from_string(input.to_s)
end
end

class NoisyString < Virtus::Attribute
lazy true

Expand All @@ -22,6 +42,9 @@ class User
attribute :name, String
attribute :scream, NoisyString
attribute :expression, RegularExpression
attribute :id, ExternalObjectId
attribute :other_ids, Array[ExternalObjectId]
attribute :alias_ids, Hash[ExternalObjectId => ExternalObjectId]
end
end
end
Expand All @@ -39,4 +62,36 @@ class User
expect(subject.scream).to eq('WELCOME')
end

context 'with a primitive defined' do
specify 'allows you to define coercion methods' do
subject.id = '53e51e803f30e1037e0008ac'
expect(subject.id).to eq(
Examples::ExternalObjectId.from_string('53e51e803f30e1037e0008ac')
)
end

context 'when used as an array member' do
specify 'coerces array members' do
subject.other_ids = [
'53e51eee3f30e1037e002c01', '53e51eee3f30e1037e002c02'
]

expect(subject.other_ids).to eq([
Examples::ExternalObjectId.from_string('53e51eee3f30e1037e002c01'),
Examples::ExternalObjectId.from_string('53e51eee3f30e1037e002c02')
])
end
end

context 'when used as a Hash key and/or value members' do
specify 'coerces key and value members' do
subject.alias_ids = { :one => 'two', 'three' => :four }
expect(subject.alias_ids).to eq({
Examples::ExternalObjectId.from_string('one') => Examples::ExternalObjectId.from_string('two'),
Examples::ExternalObjectId.from_string('three') => Examples::ExternalObjectId.from_string('four')
})
end
end
end

end