Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions lib/virtus/instance_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
12 changes: 11 additions & 1 deletion spec/integration/default_values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down