Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created May 13, 2015 18:40
Show Gist options
  • Save mayfer/c1361fb32b07d628c687 to your computer and use it in GitHub Desktop.
Save mayfer/c1361fb32b07d628c687 to your computer and use it in GitHub Desktop.
require 'pg'
CONN = PG::Connection.new({
host: 'localhost',
user: 'murat',
password: '',
dbname: 'lighthouse_2015_05'
})
class Orm
def initialize(attributes)
attributes.each do |key, value|
instance_key = "@#{key}"
# set the value of the instance var
instance_variable_set(instance_key, value)
# generate getter & setter
self.class.__send__(:attr_accessor, key)
end
end
def get_attributes
vars = []
instance_variables.each do |item|
if item != :@id
vars << item[1..-1]
end
end
vars
end
def get_key_value_strings
get_attributes.map do |key|
value = instance_variable_get("@#{key}")
"#{key} = '#{value}'"
end
end
def self.table_name
"#{self.to_s.downcase}s"
end
def save
if @id
key_value_list = get_key_value_strings.join(", ")
@id = @id.to_i
sql = "UPDATE #{self.class.table_name} SET #{key_value_list} WHERE id=#{@id}"
puts sql
CONN.exec(sql)
else
puts "creating"
end
end
def self.find(id)
results = CONN.exec_params("SELECT * FROM #{self.table_name} WHERE id=$1", [id])
if results.ntuples > 0
attributes = results[0]
else
return nil
end
self.new(attributes)
end
def destroy
end
def test
@table
end
end
class Contact < Orm
end
class Message < Orm
end
contact = Contact.find(1)
# SQL Injection!!! careful.
contact.name = "Tarum'; DROP TABLE contacts; -- "
contact.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment