This is a card in Dave's Virtual Box of Cards.
Ruby CGI TODO
Created: 2022-10-03
My online "TODO" web service is four dozen lines of ungolfed Ruby CGI and a text file.
The todo.txt
text file format looks like this:
x Water plants Write rest of novel x Take picture of cat x Brush teeth Buy some land somewhere
The 'x' at the beginning of the line means the item is done.
It renders like so:
When I click on one of the items, it toggles to done or undone (the first character of the text file line is toggled between ' ' and 'x'). The input at the bottom is for adding new lines.
#!/usr/bin/ruby require 'cgi' cgi = CGI.new fname="todo.txt" added_new_str = "" if cgi.has_key?('new_item') File.open(fname, 'a') do |file| file.puts " #{cgi['new_item']}" # note two spaces at beginning end end if cgi.has_key?('toggle') line = cgi['toggle'].to_i-1 lines = File.readlines(fname) lines[line][0] = lines[line][0] == "x" ? " " : "x" # toggle! File.open(fname, 'w') { |f| f.write(lines.join) } end puts "Content-Type: text/html" puts puts '<html><head><title>TODO</title> <style> body { line-height: 1.6; } a { text-decoration: none; color: #000; } a.done { text-decoration: line-through; color: #999; } </style> </head><body><h1>TODO</h1>' line_num=0 File.open(fname, 'r').each do |line| line_num += 1 item = CGI.escapeHTML(line.chomp) done = (item[0] == 'x' ? 'done' : '') item = item[2..-1] puts "<a class=\"#{done}\" href=\"?toggle=#{line_num}\">#{item}</a><br>\n" end puts '<form><input type="text" name="new_item"><input type="submit"></form> </body></html>'
Could you break this? Sure! Is it secure? HECK NO! That would probably take a problem at least len times this size and would have felt like something I should be paid to write.
This is Utopian Software!