Guest User

Untitled

a guest
Jun 17th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. require 'rubygems'
  2. require 'active_record'
  3.  
  4. class Contact < ActiveRecord::Base
  5.  
  6. begin
  7. establish_connection(:adapter => 'mysql',
  8. :database => 'contacts',
  9. :host => '127.0.0.1',
  10. :username => 'root',
  11. :password => '')
  12. rescue Exception => error
  13. STDERR.puts error
  14. end
  15.  
  16. def self.add_contact(name, address, tel, email)
  17. begin
  18. c = Contact.new(:name => name, :address => address, :tel => tel, :email => email)
  19. c.save
  20. rescue
  21. STDERR.puts 'Must specify name, address, tel and email'
  22. end
  23. end
  24.  
  25. def self.delete_contact(name)
  26. Contact.delete_all("name = '#{name}'")
  27. end
  28.  
  29. def self.edit_contact(name, address, tel, email)
  30. c = Contact.find(:first, :conditions => "name='#{name}'")
  31. c.address = address unless address.nil?
  32. c.tel = tel unless tel.nil?
  33. c.email = email unless email.nil?
  34. c.save
  35. end
  36.  
  37. def self.lookup_contact(name)
  38. Contact.find(:first, :conditions => "name = '#{name}'")
  39. end
  40.  
  41. def self.dump_contacts
  42. Contact.find(:all)
  43. end
  44.  
  45. end
  46.  
  47. if __FILE__ == $0
  48.  
  49. begin
  50. case ARGV[0]
  51. when 'add'
  52. Contact.add_contact(ARGV[1],ARGV[2], ARGV[3], ARGV[4])
  53. when 'delete'
  54. if(Contact.lookup_contact(ARGV[1]).nil?)
  55. puts 'Contact does not exist'
  56. else
  57. Contact.delete_contact(ARGV[1])
  58. end
  59. when 'edit'
  60. if(ARGV[1].nil?)
  61. puts 'Specify contact name for editing'
  62. elsif(Contact.lookup_contact(ARGV[1]).nil?)
  63. puts 'Contact does not exist'
  64. else
  65. Contact.edit_contact(ARGV[1],ARGV[2], ARGV[3], ARGV[4])
  66. end
  67. when 'lookup'
  68. puts Contact.lookup_contact(ARGV[1]).inspect
  69. when 'dump'
  70. Contact.dump_contacts.each {|c| puts c.inspect }
  71. else
  72. STDERR.puts 'Usage: contacts <add|delete|edit|lookup|dump> name address tel email'
  73. end
  74. rescue Exception => error
  75. puts error
  76. end
  77.  
  78. end
Add Comment
Please, Sign In to add comment