Permalink
Browse files

Ensure defaults are set prior to freeze objects

* As defaults are lazy-set on first access, accessing a
  attribute with a default on a previously frozen object
  blows up without this patch.

* I choose not to call #get_attributes as this creates an wasted
  attribute hash.
  • Loading branch information...
1 parent 9388527 commit 6592ba29b71e0f269ed144418629ff8cecf4d908 Markus Schirp committed Jul 19, 2012
Showing with 30 additions and 0 deletions.
  1. +30 −0 lib/virtus/instance_methods.rb
@@ -132,6 +132,36 @@ def to_hash
attributes
end
+ # Freeze object
+ #
+ # @return [self]
+ #
+ # @api public
+ #
+ # @example
+ #
+ # class User
+ # include Virtus
+ #
+ # attribute :name, String
+ # attribute :age, Integer
+ # end
+ #
+ # user = User.new(:name => 'John', :age => 28)
+ # user.frozen? # => false
+ # user.freeze
+ # user.frozen? # => true
+ #
+ # @api public
+ #
+ def freeze
+ # Call get_attribute on all attribute to ensure defaults are set prior to freezing
+ attribute_set.each do |attribute|
+ get_attribute(attribute.name)
+ end
+ super
+ end
+
private
# Get values of all attributes defined for this class, ignoring privacy

0 comments on commit 6592ba2

Please sign in to comment.