Sha256: c94ee3639a7d0aaf5c10dfbd3998ab5c1c86d801057946e29df4724e5f729bb4

Contents?: true

Size: 1.7 KB

Versions: 3

Compression:

Stored size: 1.7 KB

Contents

module Scrivito
  class CmsRestApi
    class WidgetExtractor

      # Extract widgets from a given attribute tree and return them as a flat
      # hash of widget_like => updated_attributes
      def self.call(updated_attributes, obj=nil)
        extracted_widgets = {}

        (updated_attributes.delete(:_widget_pool) || {}).each do |widget, widget_properties|
          unless widget.persisted?
            raise ScrivitoError, 'new top-level widgets are not allowed in the _widget_pool'
          end
          extracted_widgets[widget] = widget_properties
          extracted_widgets.merge!(call(widget_properties, obj))
        end

        updated_attributes.each do |attribute_name, value|
          if value.is_a?(Array) && value.all? {|w| w.is_a?(BasicWidget)}
            value.each do |widget|
              unless widget.persisted?
                attach_widget_to_obj(widget, obj)
                extracted_widgets[widget] = widget.attributes_to_be_saved
                extracted_widgets.merge!(call(widget.attributes_to_be_saved, obj))
              end
            end
          end
        end

        extracted_widgets
      end

      def self.attach_widget_to_obj(widget, obj)
        widget.id = widget.attributes_to_be_saved.delete('_id') || generate_widget_pool_id(obj)
        widget.obj = obj
      end

      def self.notify_persisted_widgets(obj, widget_hash)
        widget_hash.each do |widget, attributes|
          if attributes.present?
            widget.obj = obj
            widget.forget_unsaved_attribtues
          end
        end
      end

      def self.generate_widget_pool_id(obj)
        obj.presence ? obj.generate_widget_pool_id : BasicObj.generate_widget_pool_id
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
scrivito_sdk-0.40.0 lib/scrivito/cms_rest_api/widget_extractor.rb
scrivito_sdk-0.40.0.rc2 lib/scrivito/cms_rest_api/widget_extractor.rb
scrivito_sdk-0.40.0.rc1 lib/scrivito/cms_rest_api/widget_extractor.rb