solnic / virtus

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

Question: Is it possible to coherce an array with hashes into virtus objects? #241

Closed sporto closed 10 years ago

sporto commented 10 years ago

I have something like this:

class Book
    include Virtus.model

    attribute :name, String

    def self.all
        [
            self.new(name: 'a'),
            self.new(name: 'b'),
            ...
        ]
    end

end

So I can do: books = Book.all

But instead of doing all these self.new I will like to simply do:

def self.all
    self.some_method_that_generates_a_collection(   [
        {name: 'a}.
        {name: 'b'},
        ...
    ])
end

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.

dkubb commented 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.

sporto commented 10 years ago

@dkubb yes, that works nicely, thanks

Maybe virtus could have a convenience method for doing this.

solnic commented 10 years ago

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.

sporto commented 10 years ago

@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.

solnic commented 10 years ago

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