2015-02-09 54 views
1

我正在開發一個即將關閉的rails 3.2.8應用程序。在乾淨的層次結構中導出回形針圖像

這個程序有一個post模型has_many資產。

資產模型是回形針管理的。

class Asset < ActiveRecord::Base 
attr_accessible :post_id, :photo 
    belongs_to :post     
    has_attached_file :photo, 
        :styles => { 
         :thumb => '260x260#', 
         :normal => { 
         :geometry => '600x600>', 
         } 
        } 
end 

我需要在生產環境中登錄並運行備份在這樣的文件系統的每一張照片到另一個文件夾命令:

~/backup-folder/post-name-foo/post-name-foo-1.png 
~/backup-folder/post-name-foo/post-name-foo-2.png 
~/backup-folder/post-name-bar/post-name-bar-1.png 
~/backup-folder/post-name-bar/post-name-bar-2.png 
~/backup-folder/post-name-bar/post-name-bar-3.png 
~/backup-folder/post-name-baz/post-name-baz-1.jpg 

圖像既可以是PNG或JPG格式,大概也是JPG(大寫),並且帖子可以有任意數量的附件。

我只需要運行一次該命令,並且如果可能避免對應用程序進行更改(如安裝新的gem),我寧願。

回答

2

我會使用shell cp命令將資產複製到備份目錄;這應該比打開和閱讀Ruby中的每一項資產快得多:

require 'shellwords' 

backup_destination = '/home/app/backup_directory' 

# create the backup base directory 
FileUtils.mkdir_p backup_destination 

Post.find_each do |post| 
    # change this if you generate your 'nice' post URLs in a different manner 
    post_name  = post.to_param 
    post_backup_dir = File.join(backup_destination, post_name) 

    FileUtils.mkdir_p post_backup_dir 

    post.assets.each_with_index do |asset, index| 
    file_extension = File.extname(asset.photo_file_name) 
    new_file_name = "#{post_name}-#{index}#{file_extension}" 

    # escape spaces in paths 
    source_path = Shellwords.shellescape asset.photo.path(:original) 
    target_path = Shellwords.shellescape File.join(post_backup_dir, new_file_name) 

    output = `cp #{source_path} #{target_path} 2>&1` 

    # make sure cp worked correctly 
    unless $?.exitstatus == 0 
     puts "WARNING: failed to copy asset #{asset.id} from #{source_path} to #{target_path}: #{output}" 
    end 
    end 
end 
+0

這真棒!謝謝你,我在不到2分鐘的時間內完成了一次完整的資產備份,你讓我的一天! – TopperH 2015-02-14 13:57:49

+0

@TopperH Sweet :)很高興聽到它爲你工作! – janfoeh 2015-02-14 13:59:05

0

下面是例子如何備份使用rake命令文件,可以增強其對文件夾備份邏輯,我希望這將有助於

  1. 創建一個耙文件中<root_folder>/lib/task/photo_backup.rake

    task :photo_backup => :environment do 
        require 'rubygems' 
        require 'rake' 
    
        # file path on production 
        filename = "post-name-foo-1.png" 
        path_to_file = "#{Rails.root.to_s}/images_folder/#{filename}" 
    
        # backup folder on production 
        backup_folder_path = "#{Rails.root.to_s}/backup_folder" 
        backup_dir = FileUtils.makedirs(backup_folder_path).first 
    
        begin 
         f = File.new("#{backup_dir}/#{filename}", "w+") 
         data = open(path_to_file).read 
         f.write(data) 
        rescue Exception => exp 
         puts("Error message : #{exp.message}") 
        ensure 
         f.close unless f == nil 
        end 
    end 
    
  2. 從控制檯執行下面的命令在你的項目根目錄。

    rake photo_backup