Skip to content
This repository has been archived by the owner on Jun 30, 2018. It is now read-only.

:class instance of a property value should be able to reference the "embedding" doc (or parent) #865

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

FestivalBobcats
Copy link

In the style of Mongoid's embedded documents, it would be nice (really nice) for property classes to reference their respective "owner" or "parent" docs (article.comments.first.article). The example below will hopefully illustrate the problem. The only existing solutions are accessor methods in the root model (e.g. article.comment_posted_within(comment)) or storing the needed attributes from the root model (such as :created_at in the test) within each embedded object, which is probably a little overkill.

class Comment
  def initialize(article, attrs)
    @article = article
    @attributes = HashWithIndifferentAccess.new(attrs)
  end

  def posted_within
    posted_at - @article.created_at
  end

  # ... method_missing and whatnot
end

class Article
  include Tire::Model::Persistence

  property :created_at, :type => 'date'
  property :comments, :class => [Comment]
end

now = Time.now
posted_at = now + 10.minutes
article = Article.new :created_at => now,
                      :comments => [{:body => 'comment body', :posted_at => posted_at}]
assert_equal article.comments.first.posted_within, 10.minutes

@FestivalBobcats
Copy link
Author

And apologies for the barrage of successive pull requests...

@karmi
Copy link
Owner

karmi commented Oct 2, 2013

I understand the motivation, and think this would work, but I'm just a bit wary about changing the instantiation in persistence/attributes -- all the models would have to respect this signature. That would also mean breaking incompatibility with existing code.

If we could somehow keep the method signature, I'm all for adding it, ideally "injecting" it from the outside?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants