module Fiona7 module Builder class IndirectBlobBuilder def initialize(obj, filename, file=nil) @obj = obj @filename = filename @file = file end def call # only publication type can contain children (code = "5") if @obj.obj_type_code != "5" || @obj.id == 2001 parent_path = "/_uploads/#{@obj.id}" else parent_path = "#{@obj.path}/_uploads" end parent = ensure_parent_exists(parent_path) ext = ::File.extname(@filename).to_s[1..-1] name = ::File.basename(@filename, '.' + ext.to_s) obj_class = if ['jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff'].include?(ext) 'X_Image' else 'X_Generic' end if @file upload = WriteObj.upload(@file, ext, {name: name, parent: parent, obj_class: obj_class}).tap(&:release!) else upload = WriteObj.create({name: name, parent: parent, obj_class: obj_class}).tap(&:release!) end end protected # TODO: extract this code def ensure_parent_exists(path) remaining = path.split("/") current = [] paths = [] original = path while !remaining.empty? current.push(remaining.shift) path = current.join('/').presence || '/' paths.push(path) end # TODO: add an optimization for exiting parents 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 def name_and_parent_path_from_path(path) components = path.split('/') name = components.pop.presence parent_path= components.join('/').presence || '/' return name, parent_path end end end end