Skip to content

Instantly share code, notes, and snippets.

@sarony
Created October 14, 2013 13:49
Show Gist options
  • Save sarony/6975928 to your computer and use it in GitHub Desktop.
Save sarony/6975928 to your computer and use it in GitHub Desktop.
require 'SQLite3'
class Student
attr_accessor :name, :twitter, :linkedin, :facebook, :website
attr_reader :id
ATTRIBUTES = {
:id=>"INTEGER PRIMARY KEY AUTOINCREMENT", :name=>"TEXT", :twitter=>"TEXT", :linkedin=>"TEXT", :facebook=>"TEXT", :website=>"TEXT"
}
@@students = []
@@db=SQLite3::Database.new('studentsNew.db')
def initialize
if @@students.count == 0
@id = 1
else
@id = @@students.max_by { |s| s.id }.id + 1
end
@@students << self
@saved = false
end
def self.reset_all
@@students.clear
end
def self.all
@@students
end
def self.find_by_name(name)
@@students.select { |s| s.name == name }
end
def self.find(id)
@@students.select { |s| s.id == id }.first
end
def self.delete(id)
@@students.reject! { |s| s.id == id}
end
def self.columns_for_sql
dayum = ATTRIBUTES.collect do |key, value|
"#{key} #{value}"
end
dayum.join(", ")
end
def insert
sql="INSERT INTO #{self.class.table_name} (#{self.columns_for_sql}) VALUES (#{self.question_marks});"
@@db.execute(sql)
end
def self.table_name
"#{self.to_s}"
end
def self.attribute_keys
ATTRIBUTES.keys
end
def get_accessors
self.send(self.class.attribute_keys)
end
def get_values_for_sql
end
def self.create_table
table="CREATE TABLE IF NOT EXISTS #{self.table_name} (#{self.columns_for_sql});"
@@db.execute(table)
end
self.create_table
end
# insert
# insert the attributes of the instance into a sql table
# get all the attributes.keys
# find the methods/attr_accessors of those keys (.send(attributes.keys))
# join (attributes.key and the attr_accessors for those keys) => ("attributes.key" "attr_accessors")
# create the number of ?s as there are attributes.keys => ("?, ?, ?, ?, ?")
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment