solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 229 forks source link

example on member coercions #171

Closed hjblok closed 11 years ago

hjblok commented 11 years ago

The note on member coercions includes the following example using a subclass of an Array:

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' }

When I run this example library.books.class is an Array and not a BookCollection. So I added a default value to the attribute :books:

attribute :books, BookCollection[Book], default: BookCollection.new

Should this be added to the docs?

solnic commented 11 years ago

Not really, it's been fixed in master.

hjblok commented 11 years ago

Okay thanks! And for reference, which commit fixes this issue?

solnic commented 11 years ago

@hjblok ugh it was a huge refactor so it's hard for me to find the exact commit sorry