Sha256: 5b09c1ca21110a874346b6f5a30ec51f3622b97a927fb9f8aa42d9618cce5ca3

Contents?: true

Size: 1.51 KB

Versions: 5

Compression:

Stored size: 1.51 KB

Contents

# encoding: UTF-8

module Spontaneous::Model::Page
  module Singleton
    extend Spontaneous::Concern

    module SiteMethods
      def singletons
        @singletons ||= {}
      end

      def singleton?(label)
        singletons.key?(label.to_s)
      end

      def add_singleton_class(type, labels)
        ([type.name.demodulize.underscore] + labels).map(&:to_sym).each do |label|
          singletons[label.to_s] = true
          define_singleton_method(label) { type.instance }
        end
      end
    end

    module AllowedTypeMethods
      def exclude_type?(type)
        return true if (type.singleton? && type.exists?)
        super
      end
    end

    module ContentClassMethods
      def singleton?
        @is_singleton || false
      end
    end

    module ClassMethods
      def singleton(*labels)
        @is_singleton = true
        extend  SingletonClassMethods
        include SingletonInstanceMethods
        set_singleton_aliases(labels)
      end
    end

    module SingletonClassMethods
      def set_singleton_aliases(labels)
        schema.site.add_singleton_class(self, labels)
      end

      def instance
        mapper.with_cache("#{self}_singleton_instance") { first }
      end

      def exists?
        !instance.nil?
      end

      def export(user = nil)
        super.merge(is_singleton: true)
      end
    end

    module SingletonInstanceMethods
      def before_save
        raise Spontaneous::SingletonException.new(self) if (new? && model.exists?)
        super
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta10 lib/spontaneous/model/page/singleton.rb
spontaneous-0.2.0.beta9 lib/spontaneous/model/page/singleton.rb
spontaneous-0.2.0.beta8 lib/spontaneous/model/page/singleton.rb
spontaneous-0.2.0.beta7 lib/spontaneous/model/page/singleton.rb
spontaneous-0.2.0.beta6 lib/spontaneous/model/page/singleton.rb