Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Last active January 31, 2016 19:47
Show Gist options
  • Save KamilLelonek/0f5987349e7d4691f415 to your computer and use it in GitHub Desktop.
Save KamilLelonek/0f5987349e7d4691f415 to your computer and use it in GitHub Desktop.
Defensive FileWriter in Ruby
class DefensiveFileWriter
def write(path, contents)
fail_if_empty_contents(contents)
fail_if_file_exist(path)
write_file(path, contents)
end
private
def fail_if_empty_contents(contents)
raise 'Nothing to write!' if empty_contents?(contents)
end
def empty_contents?(contents)
contents.nil? || contents.empty?
end
def fail_if_file_exist(path)
raise 'File already exists!' if file_exist?(path)
end
def file_exist?(path)
File.exist?(path) && !File.zero?(path)
end
def write_file(path, contents)
IO.write(path, contents)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment