Sha256: eaf79f353c9139ef16136fdd810c803456985b2a44beff8a4fd136fa885f2096

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

module Scrivito
  class RestrictionSet
    Restriction = Struct.new(:attribute, :callable) do
      def call(obj)
        if skip?(obj)
          false
        else
          value = obj[attribute]

          callable.call(value)
        end
      end

      private

      def skip?(obj)
        !obj.has_attribute?(attribute) || obj.type_of_attribute(attribute) == 'widget'
      end
    end

    def add(options, &block)
      options = options.with_indifferent_access
      attribute = options.fetch(:uses) do
        raise ScrivitoError, 'No "uses" option given when adding a publish restriction'
      end

      unless block_given?
        raise ScrivitoError, 'No block provided when adding a publish restriction'
      end

      restrictions << Restriction.new(attribute, block)
    end

    def restriction_messages_for(obj)
      restriction_messages = restrictions.inject([]) do |messages, restriction|
        message = restriction.call(obj)

        if message
          messages << message.to_s
        end

        messages
      end

      restriction_messages.uniq
    end

    private

    def restrictions
      @restrictions ||= []
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
scrivito_sdk-0.17.0 lib/scrivito/restriction_set.rb