module Scrivito # Represents a collection of {Scrivito::Attribute} instances. It provides convienient ways to # find and add attributes and is returned by {Scrivito::ObjClass#attributes}. It behaves almost # exactly as an Array, so methods like `#each`, `#select` etc. are available. It is not necessary # to manually create an {Scrivito::AttributeCollection}, because a simple Array with attributes # can be used instead. # # @api public class AttributeCollection include Enumerable extend Forwardable # Initializes an attribute collection for an obj class. # # @param [Scrivito::ObjClass] obj_class # @param [Array] attributes # @return [Scrivito::AttributeCollection] def initialize(obj_class, attributes) @obj_class = obj_class @attributes = attributes end # Yields successive attributes of the collection. Implements the {Enumerable} interface. # @api public def_delegators :@attributes, :each # Finds an attribute in this collection by its name. # # @api public # # See {Scrivito::ObjClass#attributes} for example of how to find an attribute by name. # # @param [String] name # @return [Scrivito::Attribute] # @raise [Scrivito::ResourceNotFound] Raised when no attribute with the given +name+ can be found. def [](name) attribute = @attributes.detect { |attribute| attribute.name == name.to_s } unless attribute raise ResourceNotFound, "Could not find #{Attribute} with name '#{name}' for" \ " obj class '#{@obj_class.name}'." end attribute end # Adds an attribute to this collection and updates the obj class. # # @api public # # See {Scrivito::ObjClass#attributes} for example of how to add an attribute. # # @param [Scrivito::Attribute, Hash] attribute The attribute to add. Can be either an attribute # instance or an attribute property hash. # @return [Scrivito::AttributeCollection] def add(attribute) attribute = Attribute.new(attribute) unless attribute.respond_to?(:to_cms_rest_api) @attributes << attribute @obj_class.update(attributes: @attributes) self end alias_method :<<, :add # Deletes all attributes from this collection that are equal to the given attribute. def_delegators :@attributes, :delete end end