jgaskins/perpetuity — Issue #1: Associations
Author: jgaskins
Created: 2012-02-07 11:29:58+00:00
State: open

I'm trying to decide how to deal with relationships between objects. Let's say we have two classes, `Article` and `Comment`. An `Article` should have a collection of `Comment`s associated with it.

There are a couple ways we can do this. One way would be to explicitly call the CommentMapper, like so:

```ruby
article = ArticleMapper.retrieve article_id
comments = CommentMapper.comments_for article
```

Or we could go with something like

```ruby
article = ArticleMapper.retrieve article_id
comments = article.comments
```

The first example seems to be the most true to the Data Mapper pattern, but the second one is ridiculously convenient and can be done with a little metaprogramming. If we are storing the `article_id` field inside each Comment record, we could define a method on the article object when it's retrieved that retrieves its comments if they haven't been retrieved, something like:

```ruby
article.instance_eval do
def comments
@comments ||= Comment.retrieve(article_id: self.id)
end
end
```

This method wouldn't exist before retrieving the article, which means it would fall back to its attr_reader or whatever method it was using as its comments attribute. I'm pretty sure this violates the Data Mapper pattern and just moves back toward the ActiveRecord pattern, unfortunately. I just like the convenience of it.