Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created October 15, 2014 17:23
Show Gist options
  • Save mayfer/8566ca3f82fbb4932b24 to your computer and use it in GitHub Desktop.
Save mayfer/8566ca3f82fbb4932b24 to your computer and use it in GitHub Desktop.
Simple ORM livecoding
class ORM
def save
if defined? @id
sql_update
else
sql_insert
end
end
def sql_insert
# get names of all instance variables
instance_vars = self.instance_variables.map { |iv| iv.to_s.sub('@', '') }
# join them by commas into one string
columns = instance_vars.join(', ')
# get the values of all instance variables wrapped in quotes
values = instance_vars.map { |iv| "'#{self.instance_variable_get("@#{iv}")}'" }
values = values.join(', ')
# generate table name from class name, lowercase and pluralized
# (i mean, we could set it manually, but we'll just do it this way just cause)
table = "#{self.class.name.downcase}s"
sql = "INSERT INTO #{table} (#{columns}) VALUES (#{values})"
# @id = execute(sql).return_id
@id = 1
sql
end
def sql_update
table = "#{self.class.name.downcase}s"
instance_vars = self.instance_variables.map { |iv| iv.to_s.sub('@', '') }
# generate the assignment parts of the sql update statement and join them by commas
assignments = instance_vars.map do |iv|
value = self.instance_variable_get("@#{iv}")
assignment = "#{iv}='#{value}'"
end.join(', ')
sql = "UPDATE #{table} SET #{assignments} WHERE id=#{@id}"
end
end
class Hand < ORM
attr_accessor :num_fingers, :nail_length
end
class User < ORM
attr_accessor :username, :email, :gender
def initialize(username, email)
@username = username
@email = email
@gender = gender
end
end
user = User.new("murat", "[email protected]")
puts user.sql_insert
# user.id => 1
user.username = "tarum"
user.email = "[email protected]"
puts user.sql_update
hand = Hand.new
hand.num_fingers = 4
hand.nail_length = "2mm"
# should produce insert statement
puts hand.save.inspect
hand.num_fingers = 5
# should produce update statement
puts hand.save.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment