ContentGroupers concern

This commit is contained in:
Andrew Brown 2016-05-03 14:23:28 -05:00
parent ffdb9c7b26
commit c39a644aff
4 changed files with 24 additions and 22 deletions

View File

@ -14,27 +14,11 @@ class Character < ActiveRecord::Base
belongs_to :universe
# TODO: Rip all this out into a HasSiblings concern (or better yet, generalize it into a HasRelationship concern)
has_many :siblingships
has_many :siblings, through: :siblingships
accepts_nested_attributes_for :siblingships, reject_if: :all_blank, allow_destroy: true
has_many :inverse_siblingships, class_name: 'Siblingship', foreign_key: 'sibling_id'
has_many :inverse_siblings, through: :inverse_siblingships, source: :character
include HasContentGroupers
# Fathership
has_many :fatherships
has_many :fathers, through: :fatherships
accepts_nested_attributes_for :fatherships, reject_if: :all_blank, allow_destroy: true
has_many :inverse_fatherships, class_name: 'Fathership', foreign_key: 'father_id'
has_many :inverse_fathers, through: :inverse_fatherships, source: :character
# TODO: design DSL in concern to condense these 5-line blocks into 1
# Mothership
has_many :motherships
has_many :mothers, through: :motherships
accepts_nested_attributes_for :motherships, reject_if: :all_blank, allow_destroy: true
has_many :inverse_motherships, class_name: 'Mothership', foreign_key: 'mother_id'
has_many :inverse_mothers, through: :inverse_motherships, source: :character
relates :siblings, with: :siblingships
relates :fathers, with: :fatherships
relates :mothers, with: :motherships

View File

@ -0,0 +1,20 @@
require 'active_support/concern'
module HasContentGroupers
extend ActiveSupport::Concern
included do
# relates :siblings, with: :siblingships
# Defines :siblings and :siblingships relations, their inverses, and accepts nested attributes for the connecting class
def self.relates relation, with: nil
singularized_relation = relation.to_s.singularize
connecting_class = with
has_many connecting_class
has_many relation, through: connecting_class
accepts_nested_attributes_for connecting_class, reject_if: :all_blank, allow_destroy: true
has_many "inverse_#{connecting_class}".to_sym, class_name: "#{singularized_relation.capitalize}", foreign_key: "#{singularized_relation}_id"
has_many "inverse_#{relation}".to_sym, through: "inverse_#{connecting_class}".to_sym, source: :character
end
end
end

View File

@ -1,2 +0,0 @@
class Mothership < ActiveRecord::Base
end