Created
March 24, 2020 21:30
-
-
Save alexshagov/627b4b68956207c776ad32c0268fcc93 to your computer and use it in GitHub Desktop.
Archive creator OOP draft
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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