Skip to content

Instantly share code, notes, and snippets.

@beforeyouknowit
Forked from mayfer/book_orm.rb
Last active August 29, 2015 14:09
Show Gist options
  • Save beforeyouknowit/e9050275f5cd229fa1ec to your computer and use it in GitHub Desktop.
Save beforeyouknowit/e9050275f5cd229fa1ec to your computer and use it in GitHub Desktop.
# This example demonstrates how to generate SQL statements
# to fetch and save objects to a database.
# Warning: It does not do the actual database calls. just returns the statements.
class Book
attr_accessor :id, :title, :author_id, :subject_id
def initialize(id, title, author_id, subject_id)
@id = id
@title = title
@author_id = author_id
@subject_id = subject_id
end
def to_s
@title
end
def save
if @id
update
else
create
end
end
def update
# make sure to use escaped arguments when you implement this yourself.
# (with placeholders instead of actual values being passed into the string)
sql = "UPDATE books SET title=#{@title} WHERE id=#{id}"
end
def create
sql = "INSERT INTO books (title) VALUES (#{@title})"
end
def all
sql = "SELECT * FROM books"
end
def self.search(terms)
sql = "SELECT * FROM books WHERE title ILIKE '%#{terms}%'"
# CONNECTION does not exist, replace it with your own SQL connection object and exec call
results = CONNECTION.execute(sql)
books = []
results.each do |row|
book = Book.new(row["id"], row["title"], row["author_id"], row["subject_id"])
books << book
end
books
end
end
results = Book.search("space")
puts results
book = Book.new
book.title = "How to confuse students in a lecture"
puts book.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment