Sequel_and_pattern_matching
Just a small example. The program takes arguments --insert
, --delete
and --list
.
It connects to a sqlite database with three fields: id
, title
and text
.
The Ratz thing is my module for user arguments.. one could use slop
, optimist-xl
or rationalist
instead (or check ARGV one-self).
The case in
is the pattern-matching.. if user argument hash has certain keys.. it performs certain actions.
To be usable, this code should perform more checks; allow searches; list with filter; adding tags to notes.. and more.
%w|sequel rainbow/refinement tempfile mw_ratz.rb|.map { require it }
DB = Sequel.connect('sqlite://notes.db')
# list all notes
def show_all
using Rainbow
puts ('-'*80).blue
DB[:notes].each {
puts " #{it[:id]} #{it[:title]}".upcase.yellow.underline
puts it[:text].chomp.faint.orange, ('-'*80).blue
}
end
# insert new note
def insert(title, text) = DB[:notes].insert(title: title, text: text)
# delete note per ID
def delete_id(id)
abort('ArgumentError id: (%s) not Integer.' % id) unless Integer === id
DB[:notes].where(id: id).delete
end
# get text from nvim editor (temp-file)
def vim_text
Tempfile.create {|tf|
system('nvim %s' % tf.path)
return File.read(tf.path)
}
end
# Get user arguments
i = Ratz.() {
str :Insert
num :Delete
bool :List, :Help
}
# Handle arguments
case i
in insert: then insert(i[:title], vim_text)
in delete: then delete_id(i[:delete])
in list: then show_all
in help: then puts <<~HELP
----------------------------------
--insert|-i TITLE Insert a note
--delete|-d ID Delete a note
--list|-l List all notes
--help|-h Show help
----------------------------------
HELP
else puts 'Unknown option.'
end