Skip to content

Instantly share code, notes, and snippets.

@katiesmillie
Last active August 29, 2015 14:13
Show Gist options
  • Save katiesmillie/cbbe037ba09a8bf75a6b to your computer and use it in GitHub Desktop.
Save katiesmillie/cbbe037ba09a8bf75a6b to your computer and use it in GitHub Desktop.
Code for Hacker School Application. I had never written anything from scratch, so I decided to tackle something that mimicked the basic functionality one of my side projects, a Rails app called dearfuture.me.
#!/usr/bin/env ruby
require 'yaml'
require 'date'
unless File.exist?("notes.yaml")
File.new "notes.yaml", "w"
end
note_struct = Struct::new("NoteStruct", :message_date, :message, :days_ago)
file = File.open "notes.yaml", "r"
YAML.load_documents(file).each_with_index do |note, index|
date = note.message_date
if Date.parse(date) <= DateTime.now
puts "
You have an unread message from #{note.days_ago} days ago:
#{note.message}"
elsif index == 0
File.open('notes.yaml', 'w') {|file| file.puts note.to_yaml }
else
File.open('notes.yaml', 'a') {|file| file.puts note.to_yaml }
end
end
puts "\nTime to fire up the flux capacitor and send a note to your future self.
How many days into the future would you like to send your note?"
days = gets.to_i
i = Time.now.to_i
message_time = (days*86400) + i
message_date = DateTime.strptime("#{message_time}",'%s').strftime("%B %d, %Y")
puts "Type your message and return to send."
message = gets.chomp
note = note_struct.new "#{message_date}", "#{message}", "#{days}"
file = File.open "notes.yaml", "a"
file.puts note.to_yaml
puts "~ ~ ~ \n Great Scott! Your message is now traveling #{days} days to the future.\n~ ~ ~"
@austenito
Copy link

Does this look better overall? Do I need to take out more whitespace, not 100% sure where to create
breaks.

It looks much better!

Re: the logic of treating the first item in my array different, I agree it's weird.

You had the right idea of trying to update a 'read' key in the yaml file. YAML is a set of keys and values so you should be able to overwrite/create new keys. Check out: http://stackoverflow.com/questions/14532959/how-do-you-save-values-into-a-yaml-file

The thought process around YAML files is:

  • Read YAML file into a ruby object (probably a hash of some sort)
  • Mutate the hash. Update it's values, remove keys, add keys.
  • Dump the new YAML file into the existing YAML file.

Ruby will overwrite keys with new values, remove keys that don't exist, and create new keys.

I do think it would be a good thing to pair on. If anything, it's something interesting to talk about during your pairing interview.

How you would validate the presence of "anything"?

You could count the number of characters in the user input and disallow empty messages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment