Can property be a list of any object?
michaelkirk opened this issue · comments
I see how, as long as the object implementes json_create and to_json, we can use it as a type of property.
What's the simplest way to have a property be a list of a particular type without implementing a boilerplate "ListofMyObject" class?
Thanks for any help.
M
the simplest way would be to just add objects of that class to the list. if you want some kind of guard to make sure no one adds objects of other types to the list you could overwrite the setter, e.g.
def my_list=(value)
raise ArgumentError if value.find{|item| !item.is_a?(MyListType)}
super
end
But when you load a document, the list won't be cast appropriately.
This is my current solution to that:
# book.rb
class Book
property :chapters, :type => ChapterArray, :default => ChapterArray.new
end
#chapter_array.rb
class ChapterArray < Array
def self.json_create(hashes)
chapters= hashes.map {|h| Chapter.json_create(h)}
return ChapterArray.new(chapters)
end
end
One of the things I like about couchdb vs. a relation database is the ability to store a one-to-many relationship within the document, without having to do a join.
Do you think it would make sense to allow the property method to have a cardinality parameter, and encapsulate this pattern of casting a list of a type? Or am I opening a can of worms?
yes it will, as long as the hashes in the document have the appropriate ruby_class
attribute.
CouchRest has an option where you can say something like this:
property :my_list, type: [MyType]
This could be added to couch potato, so far nobody has bothered yet.
Just in case anyone is following this, "property" was pulled out of CouchRest into the CouchRest Extended document gem, which in turn seems to have been superseded by CouchRest Model[1]
I haven't looked into much, but it seems like CouchRest Model is leveraging a lot of the ActiveModel code from Rails3.
Thanks for the lead Alexander.
btw. so is couch potato. it uses callbacks and dirty tracking and is activemodel compliant.