DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Leave_comment.rb - Prints A Comment With Various Informations To The Screen, Or Appends To A Database File

04.13.2010
| 1981 views |
  • submit to reddit
        
#!/usr/bin/ruby

# $ ruby leave_comment.rb usage
#Usage: "ruby leave_comment.rb 'Comment' ['Name' | '"Full Name"'] [optional: 'save_to_file']"

# Comment entry class
class Comment
  def initialize(comment, name)
    @comment = comment
    @name    = name
  end

  def to_str
    date = Time.now.strftime("%m/%d/%Y")
    time = Time.now.strftime("%H:%M:%S")
    "\"Comment: #@comment\"\n" + "Posted on " + date + " at " + time + " by #@name"
  end
end

# Command-line arguments
# ARGV[0] = Comment
# ARGV[1] = Name | "Full Name"
# ARGV[2] = Optional Command Module

cmd_comment = ARGV[0]
cmd_name    = ARGV[1]
cmd_command = ARGV[2]

# Not enough arguments
if ARGV.length < 2 && ARGV.length > 0 && cmd_comment != "usage"
  puts "Not enough arguments! Usage: \"ruby #$0 'Comment' ['Name' | '\"Full Name\"'] [optional: 'save_to_file']\"\n\n"
  
# Print entry to screen
elsif ARGV.length == 2
  entry = Comment.new(cmd_comment, cmd_name)
  entry_str = entry.to_str
  puts entry_str + "\n\n"

# Save to file
elsif ARGV.length == 3 && cmd_command == "save_to_file"
  entry = Comment.new(cmd_comment, cmd_name)
  entry_str = entry.to_str

  filename = $0.chomp(File.extname($0))
  filename = filename + ".db"
  entry_file = File.new(filename, "a")

  if entry_file
    entry_file.syswrite(entry_str + "\n\n")
    puts "Saved to #{filename}!\n\n"
  else
    puts "Unable to open #{filename}!\n\n"
  end

# Invalid command module
elsif ARGV.length >= 3 && cmd_command != "save_to_file"
  puts "Invalid optional command! Available optional modules: 'save_to_file'\n\n"

# Print usage instructions
elsif cmd_comment == "usage"
  puts "Usage: \"ruby #$0 'Comment' ['Name' | '\"Full Name\"'] [optional: 'save_to_file']\"\n\n"

# No arguments, print file to screen
elsif ARGV.length == 0
  puts "No arguments! Usage: \"ruby #$0 'Comment' ['Name' | '\"Full Name\"'] [optional: 'save_to_file']\"\n\n"
end