module Polygallery module HasPolyphotos extend ActiveSupport::Concern included do def defaults klass = self.class_name.present? ? Kernel.const_get(self.class_name) : Gallery klass::DEFAULTS end end module ClassMethods def has_polyphotos(title='photos', options={}) if title.is_a? Hash options = title title = 'photos' end # raise 'BOOM' if options.keys.any? settings = options has_many title.to_sym, settings[:associations][:photos] accepts_nested_attributes_for title.to_sym, settings[:nested_attributes][:photos] # TODO: get the actual settings somehow after_initialize do # raise galleryable_type if galleryable_type.present? send(title.to_sym).build( :galleryable_id => galleryable_id, :galleryable_type => galleryable_type, :gallery_title => self.title ) unless send(title.to_sym).any? end include HasPolyphotos::LocalInstanceMethods end end module LocalInstanceMethods def set_nest(photo) photo.gallery ||= self photo.galleryable_id ||= galleryable_id photo.galleryable_type ||= galleryable_type photo.gallery_title ||= title end end end end ActiveRecord::Base.send :include, Polygallery::HasPolyphotos