Permalink
Browse files

Add Attribute#defined? to return if attribute value has been defined

  • Loading branch information...
1 parent 79f66db commit d84f4df38f40ed70917137d128f15d56644f4144 @amarshall amarshall committed Jan 31, 2014
Showing with 31 additions and 0 deletions.
  1. +11 −0 lib/virtus/attribute/accessor.rb
  2. +20 −0 spec/unit/virtus/attribute/defined_spec.rb
@@ -34,6 +34,17 @@ def self.extended(descendant)
descendant.instance_variable_set('@instance_variable_name', "@#{name}")
end
+ # Return if attribute value is defined
+ #
+ # @param [Object] instance
+ #
+ # @return [Boolean]
+ #
+ # @api public
+ def defined?(instance)
+ instance.instance_variable_defined?(instance_variable_name)
+ end
+
# Return value of the attribute
#
# @param [Object] instance
@@ -0,0 +1,20 @@
+require 'spec_helper'
+
+describe Virtus::Attribute, '#defined?' do
+ subject { object.defined?(instance) }
+
+ let(:object) { described_class.build(String, :name => name) }
+
+ let(:model) { Class.new { attr_accessor :test } }
+ let(:name) { :test }
+ let(:instance) { model.new }
+
+ context 'when the attribute value has not been defined' do
+ it { should be(false) }
+ end
+
+ context 'when the attribute value has been defined' do
+ before { instance.test = nil }
+ it { should be(true) }
+ end
+end

0 comments on commit d84f4df

Please sign in to comment.