Permalink
Browse files

Make relationship definitions inheritable

Makes it so subclasses automatically inherit a copy of their
superclass' relationship metadata. This allows subclasses of a class
including Her::Model to work as expected.
  • Loading branch information...
1 parent d1f443a commit 4c6a5f79586e8d7bfc5a803320fd1e6f5ed22f12 @thomsbg thomsbg committed with Aug 10, 2012
Showing with 14 additions and 11 deletions.
  1. +14 −11 lib/her/model/relationships.rb
@@ -2,18 +2,24 @@ module Her
module Model
# This module adds relationships to models
module Relationships
- # Return relationships
+ # Return @her_relationships, lazily initialized with copy of the
+ # superclass' her_relationships, or an empty hash.
# @private
def relationships # {{{
- @her_relationships
+ @her_relationships ||= begin
+ if superclass.respond_to?(:relationships)
+ superclass.relationships.dup
+ else
+ {}
+ end
+ end
end # }}}
# Parse relationships data after initializing a new object
# @private
def parse_relationships(data) # {{{
- @her_relationships ||= {}
- @her_relationships.each_pair do |type, relationships|
- relationships.each do |relationship|
+ relationships.each_pair do |type, definitions|
+ definitions.each do |relationship|
name = relationship[:name]
klass = self.nearby_class(relationship[:class_name])
next if !data.include?(name) or data[name].nil?
@@ -49,13 +55,12 @@ def parse_relationships(data) # {{{
# @user.articles # => [#<Article(articles/2) id=2 title="Hello world.">]
# # Fetched via GET "/users/1/articles"
def has_many(name, attrs={}) # {{{
- @her_relationships ||= {}
attrs = {
:class_name => name.to_s.classify,
:name => name,
:path => "/#{name}"
}.merge(attrs)
- (@her_relationships[:has_many] ||= []) << attrs
+ (relationships[:has_many] ||= []) << attrs
define_method(name) do
klass = self.class.nearby_class(attrs[:class_name])
@@ -82,13 +87,12 @@ def has_many(name, attrs={}) # {{{
# @user.organization # => #<Organization(organizations/2) id=2 name="Foobar Inc.">
# # Fetched via GET "/users/1/organization"
def has_one(name, attrs={}) # {{{
- @her_relationships ||= {}
attrs = {
:class_name => name.to_s.classify,
:name => name,
:path => "/#{name}"
}.merge(attrs)
- (@her_relationships[:has_one] ||= []) << attrs
+ (relationships[:has_one] ||= []) << attrs
define_method(name) do
klass = self.class.nearby_class(attrs[:class_name])
@@ -115,14 +119,13 @@ def has_one(name, attrs={}) # {{{
# @user.team # => #<Team(teams/2) id=2 name="Developers">
# # Fetched via GET "/teams/2"
def belongs_to(name, attrs={}) # {{{
- @her_relationships ||= {}
attrs = {
:class_name => name.to_s.classify,
:name => name,
:foreign_key => "#{name}_id",
:path => "/#{name.to_s.pluralize}/:id"
}.merge(attrs)
- (@her_relationships[:belongs_to] ||= []) << attrs
+ (relationships[:belongs_to] ||= []) << attrs
define_method(name) do
klass = self.class.nearby_class(attrs[:class_name])

0 comments on commit 4c6a5f7

Please sign in to comment.