module Polygallery module HasPolyphotos extend ActiveSupport::Concern included do end module ClassMethods def has_polyphotos(title=nil, options={}) attr_accessor :polygallery_options defaults = self.polygallery_settings association_names = (options[:association_names].present? ? options : defaults)[:association_names] title ||= association_names[:photos].to_s if title.is_a? Hash options = title title = association_names[:photos].to_s end settings = defaults.deep_merge options init_associations settings after_initialize do self.polygallery_options ||= self.polygallery_settings self.initialize_polygallery end include HasPolyphotos::LocalInstanceMethods end def polygallery_settings HasPolygallery::DEFAULTS end def init_associations(settings=HasPolygallery::DEFAULTS) belongs_to :galleryable, :polymorphic => true photos_name = settings[:association_names][:photos] has_many photos_name, settings[:associations][:photos] accepts_nested_attributes_for photos_name, settings[:nested_attributes][:photos] end end module LocalInstanceMethods def set_nest(photo) photo.send(:"#{title}=", self) if photo.send(:"#{title}").nil? photo.galleryable_id ||= galleryable_id photo.galleryable_type ||= galleryable_type photo.gallery_title ||= title end def include_polygallery_settings(settings) self.polygallery_options = settings self.initialize_polygallery end def initialize_polygallery settings = self.polygallery_settings self.class.init_associations(settings) end def build_first_photo photo_association = self.polygallery_photos photo_association.build( :polygallery_options => self.polygallery_settings, :galleryable_id => self.galleryable_id, :galleryable_type => self.galleryable_type, :gallery_title => self.title ) unless photo_association.any? end def polygallery_settings return self.polygallery_options if self.polygallery_options.present? return Kernel.const_get(self.galleryable_type) .send(:"#{self.title}_settings") if galleryable_type.present? self.class.polygallery_settings end def polygallery_photos self.send self.polygallery_settings[:association_names][:photos] end end end end ActiveRecord::Base.send :include, Polygallery::HasPolyphotos