Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created May 15, 2009 08:01
Show Gist options
  • Save mattetti/112109 to your computer and use it in GitHub Desktop.
Save mattetti/112109 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'couchrest'
SERVER = CouchRest.new
DB = SERVER.database!('contact-manager')
class Contact < CouchRest::ExtendedDocument
use_database DB
property :first_name
property :last_name, :alias => :family_name
property :company_name
property :job_title
property :address, :cast_as => 'Address'
property :phone_numbner
property :email
timestamps!
view_by :first_name
end
class Address < Hash
include ::CouchRest::CastedModel
property :line_1
property :line_2
property :city
property :state
property :zip_code
property :country, :default => "USA"
def to_s
address_str = "#{line_1}"
address_str << ",\n #{line_2}" if line_2
address_str << "\n"
address_str << "#{city}, " if city
address_str << "#{state}" if state
address_str << " #{zip_code}" if zip_code
address_str << "\n#{country}" if country
address_str
end
end
puts "You have #{Contact.all.size} contacts"
puts "Let's add a new contact!"
matt = Contact.new(:first_name => 'Matt', :last_name => 'Aimonetti')
matt.company_name = 'm|a agile'
matt.address = Address.new(:line_1 => 'Main Street', :city => 'San Diego', :state => 'CA')
matt.address.zip_code = 92128
puts "new contact to add: #{matt.inspect}"
matt.save
puts "You now have #{Contact.all.size} contacts"
matt_from_db = Contact.first
puts "\ninspecting Matt:\n#{matt_from_db.inspect}"
puts "***"
address = matt_from_db.address
puts "checking on Matt's address:"
puts address
# create multiple users to make sure we don't cheat
%Q{joe, james, ninh, patrick, laurent, rich}.each do |name|
Contact.new(:first_name => name).save
end
puts "\n\n"
puts "find a user by first name"
found_user = Contact.by_first_name(:key => 'Matt').first
puts "#{found_user.inspect} found"
DB.delete!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment