Skip to content
Browse files

Add a note about member class coercion

Closes #114
  • Loading branch information...
1 parent acc4129 commit 4ef7e853de49ab4ce2d2b6a7519324882c415fc8 @solnic committed Oct 1, 2012
Showing with 61 additions and 1 deletion.
  1. +61 −1 README.md
View
62 README.md
@@ -1,5 +1,5 @@
-virtus
======
+virtus
[![Build Status](https://secure.travis-ci.org/solnic/virtus.png)](http://travis-ci.org/solnic/virtus)
[![Dependency Status](https://gemnasium.com/solnic/virtus.png)](https://gemnasium.com/solnic/virtus)
@@ -223,6 +223,66 @@ package = Package.new(:dimensions => { 'width' => "2.2", :height => 2, "length"
package.dimensions # => { :width => 2.2, :height => 2.0, :length => 4.5 }
```
+### IMPORTANT note about member coercions
+
+Virtus performs coercions only when a value is being assigned. If you mutate the value later on using its own
+interfaces then coercion won't be triggered.
+
+Here's an example:
+
+``` ruby
+class Book
+ include Virtus
+
+ attribute :title, String
+end
+
+class Library
+ include Virtus
+
+ attribute :books, Array[Book]
+end
+
+library = Library.new
+
+# This will coerce Hash to a Book instance
+library.books = [ { :title => 'Introduction to Virtus' } ]
+
+# This WILL NOT COERCE the value because you mutate the books array with Array#<<
+library.books << { :title => 'Another Introduction to Virtus' }
+```
+
+A suggested solution to this problem would be to introduce your own class instead of using Array and implement
+mutation methods that perform coercions. For example:
+
+```
+``` ruby
+class Book
+ include Virtus
+
+ attribute :title, String
+end
+
+class BookCollection < Array
+ def <<(book)
+ if book.kind_of?(Hash)
+ super(Book.new(book))
+ else
+ super
+ end
+ end
+end
+
+class Library
+ include Virtus
+
+ attribute :books, BookCollection[Book]
+end
+
+library = Library.new
+library.books << { :title => 'Another Introduction to Virtus' }
+```
+
### Value Objects
``` ruby

0 comments on commit 4ef7e85

Please sign in to comment.
Something went wrong with that request. Please try again.