module Scrivito class ObjClassController < WebserviceController def defaults obj_class_name = params.fetch(:obj_class_name) obj_class = fetch_obj_class(obj_class_name) if obj_class @defaults = compute_defaults_for(obj_class) else raise ResourceNotFound, %{The obj class "#{obj_class_name}" is not available.} end end def thumbnails model_classes = [*Scrivito.models.objs, *Scrivito.models.widgets] @thumbnails = model_classes.each_with_object({}) do |model_class, hash| hash[model_class.name] = build_selection_option(model_class.name) end end private def compute_defaults_for(obj_class) if obj_class.ancestors.include?(BasicObj) compute_obj_defaults_for(obj_class) else compute_widget_defaults_for(obj_class) end end def compute_obj_defaults_for(obj_class) attributes = params.fetch(:attributes, {}).merge(_obj_class: obj_class.name) attributes = attributes.to_unsafe_h parsed_attrs = obj_params_parser.parse(attributes) base_defaults = obj_class.build_attributes_with_defaults( parsed_attrs, scrivito_user: scrivito_user) computed_nested_attributes(base_defaults, obj_class) end def compute_widget_defaults_for(widget_class) base_defaults = widget_class.build_attributes_with_defaults( { _obj_class: widget_class.name }, scrivito_user: scrivito_user) computed_nested_attributes(base_defaults, widget_class) end def computed_nested_attributes(defaults, obj_class) widget_attributes = {} other_attributes = {} defaults.each do |name, value| next if value.nil? attribute_type = obj_class.attribute_definitions[name].try(:type) if attribute_type == 'widgetlist' widgets = value.map do |new_widget| computed_nested_attributes(new_widget.attributes_to_be_saved, new_widget.class) end widget_attributes[name] = ['widgetlist', widgets] elsif attribute_type != 'binary' other_attributes[name] = value end end other_attributes = serialize(other_attributes, obj_class) widget_attributes.merge(other_attributes).merge(_obj_class: obj_class.name) end def serialize(attributes, obj_class) serializer = AttributeSerializer.new(obj_class) serializer.serialize(attributes, obj_class.attribute_definitions) end def fetch_obj_class(obj_class_name) compute_type(Widget, obj_class_name) || compute_type(Obj, obj_class_name) end def compute_type(base_class, obj_class_name) base_class.type_computer.compute_type_without_fallback(obj_class_name) rescue ObjClassNotFound nil end def obj_params_parser ObjCreateParamsParser.new(request.host, request.port) end def build_selection_option(class_name) template_path = "#{class_name.underscore}/thumbnail" begin render_to_string(template_path, layout: false, formats: :html) rescue ActionView::MissingTemplate render_to_string('scrivito/fallback_thumbnail', layout: false, formats: :html, locals: {class_name: class_name, template_path: template_path}) end end end end