Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Created October 11, 2010 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanhandley/620388 to your computer and use it in GitHub Desktop.
Save seanhandley/620388 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'active_record'
class Contact < ActiveRecord::Base
begin
establish_connection(:adapter => 'mysql',
:database => 'contacts',
:host => '127.0.0.1',
:username => 'root',
:password => '')
rescue Exception => error
STDERR.puts error
end
def self.add_contact(name, address, tel, email)
begin
c = Contact.new(:name => name, :address => address, :tel => tel, :email => email)
c.save
rescue
STDERR.puts 'Must specify name, address, tel and email'
end
end
def self.delete_contact(name)
Contact.delete_all("name = '#{name}'")
end
def self.edit_contact(name, address, tel, email)
c = Contact.find(:first, :conditions => "name='#{name}'")
c.address = address unless address.nil?
c.tel = tel unless tel.nil?
c.email = email unless email.nil?
c.save
end
def self.lookup_contact(name)
Contact.find(:first, :conditions => "name = '#{name}'")
end
def self.dump_contacts
Contact.find(:all)
end
end
if __FILE__ == $0
begin
case ARGV[0]
when 'add'
Contact.add_contact(ARGV[1],ARGV[2], ARGV[3], ARGV[4])
when 'delete'
if(Contact.lookup_contact(ARGV[1]).nil?)
puts 'Contact does not exist'
else
Contact.delete_contact(ARGV[1])
end
when 'edit'
if(ARGV[1].nil?)
puts 'Specify contact name for editing'
elsif(Contact.lookup_contact(ARGV[1]).nil?)
puts 'Contact does not exist'
else
Contact.edit_contact(ARGV[1],ARGV[2], ARGV[3], ARGV[4])
end
when 'lookup'
puts Contact.lookup_contact(ARGV[1]).inspect
when 'dump'
Contact.dump_contacts.each {|c| puts c.inspect }
else
STDERR.puts 'Usage: contacts <add|delete|edit|lookup|dump> name address tel email'
end
rescue Exception => error
puts error
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment