module Polygallery::HasPolygallery::ClassMethods

Public Instance Methods

has_polygallery(title='gallery', options={}) click to toggle source
# File lib/polygallery/has_polygallery.rb, line 7
def has_polygallery(title='gallery', options={})
  if title.is_a? Hash
    options = title
    title = 'gallery'
  end

  defaults = DEFAULT_SETTINGS
  if options[:association_names].nil? && title.to_s != 'gallery'
    options[:association_names] = {
      :gallery => :"#{title}",
      :photos => :"#{title.to_s.gsub('_gallery', '')}_photos" }
  end
  settings = defaults.deep_merge(options)
  cattr_accessor "#{title}_settings".to_sym
  send("#{title}_settings=".to_sym, settings)
  attr_accessor :"#{title}_attributes", :galleries_built

  has_one title.to_sym, -> { where(title: title.to_s) }, settings[:associations][:gallery]
  has_many settings[:association_names][:photos],
           :through => :"#{title}",
           :source => :photos, # settings[:association_names][:photos],
           :class_name => settings[:associations][:photos][:class_name]
  accepts_nested_attributes_for settings[:association_names][:gallery],
                                settings[:nested_attributes][:gallery]
  accepts_nested_attributes_for settings[:association_names][:photos],
                                settings[:nested_attributes][:photos]

  after_initialize :if => :new_record? do
    # puts "GA: #{self.gallery_attributes.inspect}"
    if self.gallery_attributes.nil?
      # puts 'BUILDING FIRST PHOTOS ON INIT!'
      build_gallery_associations
      build_first_photos
    end
  end
    # puts instance.inspect
    # instance.new_record? && !instance.has_polygallery? }
  before_validation do # , :on => :update # , :unless => :new_record?
    # puts 'BUILDING GALLERIES ON VALIDATION'
    # unless self.galleries_built?
    build_gallery_associations
    # end
    prune_empty_photos
  end
  before_save :ensure_galleryable_set

  include HasPolygallery::LocalInstanceMethods
end
has_polygallery?(gallery_title=nil) click to toggle source
# File lib/polygallery/has_polygallery.rb, line 61
def has_polygallery?(gallery_title=nil)
  return polygalleries.any? if gallery_title.nil?
  polygalleries.include?(gallery_title)
end
polygalleries() click to toggle source
# File lib/polygallery/has_polygallery.rb, line 56
def polygalleries
  self.reflect_on_all_associations(:has_one)
      .select{|a| a.foreign_key == 'galleryable_id'}.map(&:name)
end