Skip to content

Instantly share code, notes, and snippets.

@avi-flombaum
Created December 13, 2012 01:18
Show Gist options
  • Save avi-flombaum/4273222 to your computer and use it in GitHub Desktop.
Save avi-flombaum/4273222 to your computer and use it in GitHub Desktop.
require 'sqlite3'
require 'debugger'
DB = SQLite3::Database.new("studentbody.db")
create_students_table_sql = <<SQL
CREATE TABLE students
(
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT,
twitter TEXT,
facebook TEXT,
photo TEXT
);
SQL
# r
# Student.find(1) #=> <#Student>
class Student
def self.table_name
"#{self.to_s.downcase}s"
end
def self.column_names
@column_names ||= DB.execute("PRAGMA table_info([students])").map do |column_info|
column_info[1].downcase.to_sym
end
end
def self.columns_for_sql
self.column_names[1..-1].join(",")
end
self.column_names.each do |column|
attr_accessor column
define_singleton_method "find_by_#{column}" do |value|
result = DB.execute("SELECT * FROM #{self.table_name} WHERE #{column} = ?", value)
initialize_from_db(result)
end
end
# for each column name
# define a method called find_by_#colum_name
# and then somehow use that column to construct the where clause
def self.find(id)
result = DB.execute("SELECT * FROM students WHERE id = ?", id)
initialize_from_db(result)
# load the student's data from the database
# instantiate a new student
# set that students attributes wtih values from the datbase
end
def self.initialize_from_db(result)
Student.new.tap do |s|
self.column_names.each_with_index do |column_name, i|
s.send("#{column_name}=", result.flatten[i])
end
end
end
def save
if new_record?
sql = "INSERT INTO students (#{self.class.columns_for_sql}) VALUES
(#{place_holders})"
puts sql
DB.execute(sql, attributes.values)
else
# for each column name I need a column = value
sql = "UPDATE students SET #{set_clause} WHERE id = #{id}"
puts sql
DB.execute(sql, attributes.values)
end
end
def new_record?
id ? false : true
end
private
def set_clause
attributes.keys.collect{|k|
"#{k} = ?"
}.join(",")
end
def place_holders
attributes.collect{"?"}.join(",")
end
def attributes
self.class.column_names[1..-1].inject({}) do |attributes, column|
attributes[column] = self.send(column)
attributes
end
end
end
debugger
@avi = Student.find(1)
# @student = Student.new
# @student.first_name = "Avi"
# @student.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment