Skip to content

Instantly share code, notes, and snippets.

@sallysmith1337
Created July 22, 2013 03:20
Show Gist options
  • Save sallysmith1337/6051108 to your computer and use it in GitHub Desktop.
Save sallysmith1337/6051108 to your computer and use it in GitHub Desktop.
# You need to learn and master class and instance variables and moethods.
# Read these
#
# http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/ -- Methods
# http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/ -- Variables
#
require 'sequel' # Have to require this if we want to use Sequel
class Account
attr_accessor :account_holder
# This is the method that's called when
def initialize(holder_name)
@account_holder = holder_name
# First we need to create a connection to our database server
# This connection OBJECT should be an instance variable (a variable that is created with the instantiation of a new class object)
database_name = "database"
database_username = "username"
database_passowrd = "passowrd"
@DB = Sequel.connect("mysql://localhost/#{database_name}" :user=> database_username, :password=> database_password)
# Now that your'e connected to the database, you can ask it to generate a new record in your accounts table (or whatever you call it) for the new accout
# Note that we use a symbol for the table name (:table) instead of a string "table"
table_name = :accounts
@DB[table_name].insert(:name => holder_name, :balance => 0)
end
def balance
# Grab the table record for @account_holder
# return the value for the balance column
table_name = :accounts
db_item = @DB[table_name].filter(:name => @account_holder).first
return db_item[:balance]
end
def deposit(money)
# Grab the table record for @account_holder
# Update the balance field with the new value, and then save the item
table_name = :accounts
db_item = @DB[table_name].filter(:name => @account_holder).first
db_item[:balance] = db_item[:balance] + money
db_item.save # This updates the database entry for the account
end
def withdraw(money)
# Grab the table record for @account_holder
# Update the balance field with the new value, and then save the item
table_name = :accounts
db_item = @DB[table_name].filter(:name => @account_holder).first
db_item[:balance] = db_item[:balance] - money
db_item.save # This updates the database entry for the account
end
def display
end
def transfer(money, target_account)
end
end
2. Modify your “API” to allow me to do the following:
(API stands for Application Programming Interface; it is basically how someone interacts with a program)
I know they want you to intiate a class like this,
a = Account.new(account_holder: ‘Steve’)
But screw that, we'll do it like this
a = Account.new("Steve")
a.deposit(100) #should update the database to store the account balance for Steves account
puts a.balance #should print out 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment