From 9ed9ff74aa9b74ad5b28575970b1d8fb34323472 Mon Sep 17 00:00:00 2001 From: Luca Guidi Date: Tue, 5 Aug 2014 15:07:44 +0200 Subject: [PATCH] Ensure that attributes are returned after initialization --- lib/lotus/validations.rb | 13 ++++++++----- test/fixtures.rb | 6 ++++++ test/initialize_test.rb | 13 +++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 test/initialize_test.rb diff --git a/lib/lotus/validations.rb b/lib/lotus/validations.rb index 33b6cf7..4ca96e9 100644 --- a/lib/lotus/validations.rb +++ b/lib/lotus/validations.rb @@ -20,17 +20,20 @@ def valid? value = Lotus::Utils::Kernel.send(coercer.to_s, value) end - instance_variable_set(:"@#{ attribute }", value) + @attributes[attribute] = value end end end module ClassMethods def attribute(name, options = {}) - class_eval do - attributes << [name, options] - attr_reader name - end + attributes << [name, options] + + class_eval %{ + def #{ name } + @attributes.fetch(:#{ name }) + end + } end # FIXME make this private diff --git a/test/fixtures.rb b/test/fixtures.rb index 4916166..26538e8 100644 --- a/test/fixtures.rb +++ b/test/fixtures.rb @@ -1,3 +1,9 @@ +class InitializerTest + include Lotus::Validations + + attribute :attr +end + class TypeValidatorTest include Lotus::Validations diff --git a/test/initialize_test.rb b/test/initialize_test.rb new file mode 100644 index 0000000..a98d909 --- /dev/null +++ b/test/initialize_test.rb @@ -0,0 +1,13 @@ +require 'test_helper' + +describe Lotus::Validations do + describe '#initialize' do + before do + @validator = InitializerTest.new(attr: 23) + end + + it 'returns a value for the given attribute' do + @validator.attr.must_equal 23 + end + end +end