Skip to content

Instantly share code, notes, and snippets.

@PirosB3
Last active December 16, 2015 03:09
Show Gist options
  • Save PirosB3/5367518 to your computer and use it in GitHub Desktop.
Save PirosB3/5367518 to your computer and use it in GitHub Desktop.
=begin
elsif answer == 'r'
add to sentence persistance
/ ask store to retrieve sentence given its name
/ give nice error message if we don't know about the sentence
/ display sentence in some format to user
=end
class SentenceStore
def save_sentence(sentence)
File.open(file_name(sentence.name()), "w+") do |file|
file.write(sentence.content())
return true
end
end
def find_sentence(name)
chosen_file = file_name(name)
if File.exist?(chosen_file)
file_object = File.open(chosen_file, "r")
file_contents = file_object.read()
file_object.close()
return Sentence.new(name,file_contents)
else
return nil
end
end
def display_all
all_sentences = []
all_text_files = Dir.glob(".txt")
all_text_files.each do |file_name|
name = file_name.gsub(".txt", "")
all_sentences.push(find_by_name(name))
end
return all_sentences
end
private
def file_name(name)
return "#{name}.txt"
end
end
class Sentence
attr_reader("name", "content")
# @param String
# @param String
def initialize(name,content)
@name = name
@content = content
end
end
class SentenceUi
def initialize(sentence_store, io)
@store = sentence_store
@io = io
end
def main_menu
@io.puts ("Welcome to Sentence Store v1")
@io.puts ("Do you want to (l) list all sentences or (s) store a sentence or (r) retrieve a sentence?:")
answer = gets().chomp().downcase()
if answer == "s"
puts "Name of sentence"
sentence_name = gets().chomp()
puts "Give me your sentence"
sentence_content = gets().chomp()
sentence = Sentence.new(sentence_name, sentence_content)
@store.save_sentence(sentence)
puts "Sentence #{sentence.name()} has been stored!"
elsif answer == "l"
elsif answer == "r"
puts "What sentence would you like to retrieve?"
sentence_name = gets().chomp()
sentence_or_nil = @store.find_sentence(sentence_name)
if sentence_or_nil.is_a?(Sentence)
puts "Your sentence is: #{sentence_or_nil.content()}."
else
puts "Sentence was not found."
end
else
puts "I have no idea about to how #{answer} a sentence!"
end
end
end
def main(io)
sentence_ui = SentenceUi.new(
SentenceStore.new(),
io
)
loop do
sentence_ui.main_menu()
end
end
main(STDOUT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment