Skip to content

Instantly share code, notes, and snippets.

@amiel
Created November 9, 2012 19:23
Show Gist options
  • Save amiel/4047653 to your computer and use it in GitHub Desktop.
Save amiel/4047653 to your computer and use it in GitHub Desktop.
require 'virtus'
class Foo
include Virtus
attribute :id, Integer
attribute :date, Date
attribute :foo, String
def initialize(attributes = {})
super(attributes)
enforce_coercions!
end
def enforce_coercions!
self.attributes.each do |name, value|
unless self.class.attribute_set[name].value_coerced? value
self[name] = nil
end
end
end
end
describe Foo do
subject { foo }
context 'with regularly coercable strings' do
let(:foo) { Foo.new(id: '1', date: '2012-10-10', foo: 'bar') }
its(:id) { should == 1 }
its(:date) { should == Date.new(2012, 10, 10) }
its(:foo) { should == 'bar' }
end
context 'with some empty strings' do
let(:foo) { Foo.new(id: '', date: '', foo: '') }
its(:id) { should be_nil }
its(:date) { should be_nil }
its(:foo) { should == '' }
end
context 'with some empty strings' do
let(:foo) { Foo.new(id: '', date: '', foo: 'bar') }
its(:id) { should be_nil }
its(:date) { should be_nil }
its(:foo) { should == 'bar' }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment