def handle_my_document(document,kind,user,my_file,count=0)
file_name=my_file.URL
forum=user.forum
puts'>>>>>'+'Handling shared document file '+file_name.to_s+' for user '+user.nil_or.id.to_s
filepath="#{Rails.root}/public/forum_shared_files/"
if !forum.nil? then forum='Forum_'+forum.id.to_s else forum='Forum_???' end
new_filepath="/Users/hansmarmolin/Projekt/Forum/st_forum/public/uploads/document/file/#{forum}/#{
document.id}/"
source=filepath+file_name
dest=new_filepath+file_name
new_name=sanitize_my_document_name(my_file,new_filepath)
if File.exists?(source)
file_size=File.size(source)
FileUtils.mkdir_p(File.dirname(dest))
FileUtils.cp source, dest
File.rename(new_filepath+file_name,new_filepath+new_name)
count+=1
else
puts'**** '+'File '+source.to_s+' '+'does not exists'
end
return count, new_name, file_size
end
def sanitize_my_document_name(my_document,new_filepath)
name=truncate(my_document.title,40).clean
if name.blank? then name=truncate(my_document.URL, 40).clean end
name=name.gsub(' ','_')
name=name.gsub('"','')
name=name.gsub(' - ','-').gsub(' -','-').gsub('- ','-')
name=name.gsub(/[^[:word:]\.\-\+]/,"_")
if !my_document.URL.include?('.') then name+'_'+my_document.id.to_s+'.???'
else name=name+'.'+my_document.URL.split('.').last end
name=name.gsub('__','_')
name=name.gsub('_-_','-')
return name
end
def truncate(text, chars = 30)
return if text.nil?
return text if text.length<=chars
words=text.split(' ')
for n in (1..words.size)
if words[0..n].join(' ').length>chars then break end
end
if words[0..n].join(' ').length-chars>chars-words[0..n-1].join(' ').length then n=n-1 end
result=words[0..n].join(' ')
end
===================
Here are the part of the rake task that calls the methods above
puts'>>>>>'+'Creating my_document '+my_file.URL
if my_file.Uploaded_by==0 then uploader=my_file.created_by else uploader=my_file.Uploaded_by end
user=find_user(uploader)
if user.nil? then next end
document=Document.create
filecount,new_name, file_size=handle_my_document(document,'user_document',user,my_file,filecount)
document.update_attributes(:title=>my_file.title,
:kind=>'user_document',
:file=>new_name,
:file_size=>file_size,
:created_at=>my_file.created,
:updated_at=>my_file.edited)
end
____________________________________________
Hans Marmolin
St: Larsgatan 50, 58224 Linköping, Sweden