Closed sporto closed 10 years ago
@sporto what about something like:
def self.all
[
{ name: 'a' },
{ name: 'b' },
].map(&method(:new))
end
This doesn't use any special virtus features, but rather just relies on built-in ruby features.
@dkubb yes, that works nicely, thanks
Maybe virtus could have a convenience method for doing this.
The example in the readme shows how to achieve collection member coercion when you're mutating the collection via its own interface - then you need a custom collection class.
Virtus supports coercing hashes into objects if member type is set to a virtus model or an open-struct but I'm not sure if that helps in your scenario.
@solnic the main issue is that when I am working on a rails codebase I want to imitate what Active records does, which is using the same class for the instance and the collection. So having a collection class doesn't fit well. Maybe it would be nice if Virtus adds a convenience way of achieving this.
OK but not in virtus itself. It can be a virtus plugin.
On Tue, Feb 11, 2014 at 10:26 PM, Sebastian Porto notifications@github.com wrote:
@solnic the main issue is that when I am working on a rails codebase I want to imitate what Active records does, which is using the same class for the instance and the collection. So having a collection class doesn't fit well. Maybe it would be nice if Virtus adds a convenience way of achieving this.
Reply to this email directly or view it on GitHub: https://github.com/solnic/virtus/issues/241#issuecomment-34808895
I have something like this:
So I can do: books = Book.all
But instead of doing all these
self.new
I will like to simply do:So just passing an array of hashes and get a collection of virtus objects back, is this possible?
I saw the example in the readme about Book and Library, but that uses two classes, with seems unnecessary and doesn't fit with the ActiveRecord way of doing things.