Skip to content

Instantly share code, notes, and snippets.

@alexshagov
Created March 24, 2020 21:30
Show Gist options
  • Save alexshagov/627b4b68956207c776ad32c0268fcc93 to your computer and use it in GitHub Desktop.
Save alexshagov/627b4b68956207c776ad32c0268fcc93 to your computer and use it in GitHub Desktop.
Archive creator OOP draft
### lib/user_input.rb
class UserInput
class InvalidUserInput < StandardError; end
def initialize(input)
@input = input
end
def to_s
@input
end
def validate!
raise InvalidUserInput unless valid?
end
def valid?
!input.empty?
end
end
### lib/archive.rb
class Archive
ARCHIVE_EXTENSION = '.zip'.zip
attr_reader :name, :files_to_archive
def initialize(name)
@name = name
@files_to_archive = []
end
def add(file)
@files_to_archive << file
end
def create!
Zip::File.open(build_uniq_name, Zip::File::CREATE) do |zipfile|
files_to_archive.each do |file|
zipfile.add(file.filename, File.join(file.filename))
end
end
end
private
def build_uniq_name
name + Time.now.to_i.to_s + ARCHIVE_EXTENSION
end
end
### lib/txt_file.rb
class TxtFile
attr_reader :filename
def initialize(user_input, filename)
# ...
end
def create!
File.open(filename, 'a') do |f|
f.write(user_input.to_s)
end
end
end
### app.rb
module App
def self.run
user_input = UserInput.new(gets.chop)
user_unput.validate!
txt_file = TxtFile.new(user_input, 'my_file.txt')
txt_file.create!
archive = Archive.new('myarchive')
archive.add(txt_file)
archive.create!
end
end
App.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment