Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created May 13, 2015 18:49
Show Gist options
  • Save mayfer/d2dedab6a9a70e5cb4a1 to your computer and use it in GitHub Desktop.
Save mayfer/d2dedab6a9a70e5cb4a1 to your computer and use it in GitHub Desktop.
require 'active_record'
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(
:adapter => "postgresql",
:host => 'localhost',
:username => 'murat',
:password => '',
:database => 'lighthouse_2015_05',
:encoding => 'utf8',
)
class Contact < ActiveRecord::Base
validates :email, format: { with: /[\w]+@[\w]+\.[\w]+/, message: "Please enter a valid email" }
end
contacts = Contact.all
# puts contacts
murat = Contact.new(name: "Murat", email: "[email protected]", phone: "778 858 8449")
# murat.save
murat.email = "INVALID"
if murat.save
puts "success"
else
puts murat.errors.full_messages.inspect
end
# someone = Contact.find(2)
# someone.destroy
#children = Contact.where("age < ?", 12)
#children.each do |child|
# puts child.name, child.age
# end
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