diff --git a/lib/virtus/instance_methods.rb b/lib/virtus/instance_methods.rb index 4448bf66..b0fdb897 100644 --- a/lib/virtus/instance_methods.rb +++ b/lib/virtus/instance_methods.rb @@ -176,6 +176,34 @@ def reset_attribute(attribute_name) self end + # Reset all attributes to their defaults + # + # @return [self] + # + # @api public + # + # @example + # + # class User + # include Virtus + # + # attribute :age, Integer, default: 21 + # attribute :name, String, default: 'Jane' + # end + # + # user = User.new(:name => 'John', :age => 28) + # user.name # => John + # user.age # => 28 + # user.reset_attributes + # user.name # => Jane + # user.age # => 21 + # + # @api public + def reset_attributes + attributes.keys.each { |attribute_name| reset_attribute(attribute_name) } + self + end + # Set default attributes # # @return [self] diff --git a/spec/integration/default_values_spec.rb b/spec/integration/default_values_spec.rb index d9d9b1e8..7353b48c 100644 --- a/spec/integration/default_values_spec.rb +++ b/spec/integration/default_values_spec.rb @@ -15,7 +15,7 @@ class Page include Virtus attribute :title, String - attribute :slug, String, :default => lambda { |post, attribute| post.title.downcase.gsub(' ', '-') }, :lazy => true + attribute :slug, String, :default => lambda { |post, attribute| post.title && post.title.downcase.gsub(' ', '-') }, :lazy => true attribute :view_count, Integer, :default => 0 attribute :published, Boolean, :default => false, :accessor => :private attribute :editor_title, String, :default => :default_editor_title, :lazy => true @@ -59,6 +59,16 @@ def default_editor_title end.to change { subject.view_count }.to(0) end + specify 'you can reset all attributes to their defaults' do + subject.view_count = 10 + subject.editor_title = "UNPUBLISHED: Top Secret" + + subject.reset_attributes + + expect(subject.view_count).to eq(0) + expect(subject.editor_title).to eq("UNPUBLISHED: ") + end + context 'a ValueObject' do it 'does not duplicate the ValueObject' do page1 = Examples::Page.new