Sha256: 632a7919bd65ae6a2c02ee2f5be2ddcec3ee0926fbd8ad5441a4a30160c0953e

Contents?: true

Size: 1.94 KB

Versions: 2

Compression:

Stored size: 1.94 KB

Contents

module Polygallery
  module HasPolygallery
    extend ActiveSupport::Concern

    included do

    end

    module ClassMethods
      def has_polygallery(title='gallery', options={})
        defaults = Gallery::DEFAULTS
        settings = defaults.deep_merge(options)
        has_one title.to_sym, -> { where(:title => title.to_s) }, settings[:association]
        accepts_nested_attributes_for title.to_sym, settings[:nested_attributes][:gallery]
        has_many "#{title}_photos".to_sym,
                 :through => title.to_sym,
                 :source => :photos,
                 :class_name => 'Polygallery::Photo'
        attr_accessor "#{title}_settings".to_sym
        after_initialize do
          send("#{title}_settings=".to_sym, settings) if send("#{title}_settings".to_sym).nil?
          send("build_#{title.to_s}".to_sym) if send(title.to_sym).nil?
        end
        include HasPolygallery::LocalInstanceMethods
      end

      def has_polyphotos(title='photos')
        has_many title.to_sym, :class_name => 'Polygallery::Photo'
        accepts_nested_attributes_for title.to_sym, Gallery::DEFAULTS[:nested_attributes][:photo] # TODO: get the actual settings object somehow
        attr_accessor :photos_to_upload
        after_initialize do
          send(title.to_sym).build unless send(title.to_sym).any?
        end
      end

      def polygalleries
        self.reflect_on_all_associations(:has_one).select{|a| a.foreign_key == 'galleryable_id'}.map(&:name)
      end

      def has_polygallery?(title)
        self.polygalleries.include?(title)
      end
    end

    module LocalInstanceMethods
      def polygalleries
        Gallery.select('polygallery_galleries.title')
          .where(:galleryable => self)
          .group('polygallery_galleries.title')
          .map(&:title)
      end

      def has_polygallery?(title)
        polygalleries.include?(title)
      end
    end
  end
end

ActiveRecord::Base.send :include, Polygallery::HasPolygallery

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
polygallery-0.0.6 lib/polygallery/has_polygallery.rb
polygallery-0.0.5 lib/polygallery/has_polygallery.rb