module Scrivito class ObjParamsParser < Struct.new(:host, :port, :context) class UnknownWidgetAction < ScrivitoError end def parse(params) params = params.deep_dup convert_params(params) params end private def convert_field_params(params, attribute_definitions) params.each_pair do |key, value| params[key] = case type = attribute_definitions[key.to_s].try(:type) when 'binary' then parse_binary_params(value) when 'html' then ContentConversion.convert_html_links(value, host, port) when 'link' then ContentConversion.convert_link(value, host, port) when 'linklist' then ContentConversion.convert_linklist_urls(value, host, port) when 'widgetlist' then parse_widgetlist_params(value) when 'date' then DateAttribute.deserialize_from_client(value) else value end end end def parse_widgetlist_params(params) params.map do |widget_id_or_params| if widget_id_or_params.is_a?(Hash) parse_widgetlist_params_with_action(widget_id_or_params) else widget = obj.widgets[widget_id_or_params] raise_widget_not_found_error(widget_id_or_params) unless widget widget end end end def parse_widgetlist_params_with_action(params) action, widget_params = params.flatten case action when 'create' then Widget.new(widget_params, context.slice(:scrivito_user)) when 'copy' widget_id = widget_params['widget_id'] widget = Workspace.find(widget_params['workspace_id']) .objs.find(widget_params['obj_id']) .widgets[widget_id] raise_widget_not_found_error(widget_id) unless widget widget.copy else raise UnknownWidgetAction end end def parse_binary_params(params) return unless params UploadedBinary.new(params) end def raise_widget_not_found_error(widget_id) raise ResourceNotFound, "Could not find Widget with id #{widget_id}" end end end