Skip to content

Instantly share code, notes, and snippets.

@ravicious
Created August 18, 2016 17:55
Show Gist options
  • Save ravicious/97486aa66e1f37f09cb5339977a5edb6 to your computer and use it in GitHub Desktop.
Save ravicious/97486aa66e1f37f09cb5339977a5edb6 to your computer and use it in GitHub Desktop.
Reproduction of the issue with using the `primitive` method within the custom attribute class body.
# ruby reproduction.rb
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'virtus', '1.0.5'
gem 'minitest', '5.9.0', require: false
end
require 'virtus'
require 'minitest/autorun'
class FiveLetterString < Virtus::Attribute
primitive String
def primitive
options[:primitive]
end
def coerce(value)
if value.respond_to? :to_str
value.to_str[0..4]
else
value
end
end
def value_coerced?(value)
value.instance_of?(String)
end
end
class Foo
include Virtus.value_object
values do
attribute :foo, FiveLetterString
end
end
class Bar
include Virtus.value_object
values do
attribute :bar, String
end
end
class StrictFoo
include Virtus.value_object
values do
attribute :foo, FiveLetterString, strict: true
end
end
class Bug < Minitest::Test
def test_custom_coercion
foo = Foo.new(foo: 'Lorem ipsum dolor sit amet')
assert_equal 'Lorem', foo.foo
end
def test_correct_use_of_string_type
bar = Bar.new(bar: 'Lorem ipsum dolor sit amet')
assert_equal 'Lorem ipsum dolor sit amet', bar.bar
end
def test_custom_coercion_works_with_strict_mode
assert_raises Virtus::CoercionError do
StrictFoo.new(foo: nil)
end
end
end
Run options: --seed 12674
# Running:
F..
Finished in 0.001724s, 1739.7124 runs/s, 1739.7124 assertions/s.
1) Failure:
Bug#test_correct_use_of_string_type [reproduction.rb:71]:
Expected: "Lorem ipsum dolor sit amet"
Actual: "Lorem"
3 runs, 3 assertions, 1 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment