Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created April 14, 2015 17:54
Show Gist options
  • Save mayfer/4c61a39d9a44fd310e64 to your computer and use it in GitHub Desktop.
Save mayfer/4c61a39d9a44fd310e64 to your computer and use it in GitHub Desktop.
Generic ORM example, that works for any class that matches a table.
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 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]")
user.save
user.username = "tarum"
user.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment