Sha256: 9e0212290d2709f618baabf940cfbbe5576f93b11d20b34749a93781f2008e17
Contents?: true
Size: 1.65 KB
Versions: 1
Compression:
Stored size: 1.65 KB
Contents
require "fileutils" require "uri" require "net/http" class DribbbleBucketSync class Folder attr_reader :path, :shots def initialize(directory, name) name = sanitize(name) # store the path @path = File.join(directory, name) # ensure our folder exists ensure_folder_exists # create storage for the shots @shots = [] end def add_shot(shot) url = shot.image_url # add the file to the shots list filename = "#{shot.id}#{File.extname(url)}" @shots << filename # calculate the path path = File.join(@path, filename) # download if it doesn't exist unless File.exist?(path) download(url, path) end end def remove_old_shots # loop through all shots in the folder current_shot_files.each do |file| # delete file if the shot isn't in the array unless @shots.include?(File.basename(file)) FileUtils.rm(file) end end end # returns an array of existing shot files def current_shot_files Dir.glob(File.join(@path, "*.{jpg,jpeg,png,gif}")) end private # downloads a URL to a local path def download(url, destination) # parse the URL uri = URI.parse(url) # connect to the site Net::HTTP.start(uri.host, uri.port) do |http| # download the file resp = http.get(uri.request_uri) # open the local file open(destination, "wb") do |file| # write the data file.write(resp.body) end end end # ensure the folder exists def ensure_folder_exists FileUtils.makedirs(@path) end # sanitizes the folder name def sanitize(name) name.downcase.gsub(/[^\w\-\s]/, "-").gsub(/[\-\_]+/, "-").gsub(/[\-\_]*$|^[\-\_]*/, "") end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
dribbble-bucket-sync-0.0.1 | lib/dribbble_bucket_sync/folder.rb |