require 'fiona7/name_and_parent_from_path' module Fiona7 module Builder # given a path it will ensure that all objects on this path exist # (or will be created if neccessary) class ContainerChainBuilder def initialize(path) @path = path end def call ensure_parent_exists(@path) end private include NameAndParentFromPath def ensure_parent_exists(path) # in most cases the parent is allready there and there is nothing # to do here at all. if obj = WriteObj.find_by_path(obj) return obj end remaining = path.split("/") current = [] paths = [] original = path while !remaining.empty? current.push(remaining.shift) path = current.join('/').presence || '/' paths.push(path) end paths.each do |path| if !WriteObj.exists?(path: path) name, parent_path = name_and_parent_path_from_path(path) WriteObj.create!(name: name, parent_obj_id: WriteObj.find_by_path(parent_path).id, obj_class: 'X_Container') end end WriteObj.find_by_path(original) || (raise "Tried to make sure that the parent under '#{original}' exist, but it does not :(") end end end end