Skip to content

Instantly share code, notes, and snippets.

@bchase
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save bchase/e053b999ab419e3db2e9 to your computer and use it in GitHub Desktop.

Select an option

Save bchase/e053b999ab419e3db2e9 to your computer and use it in GitHub Desktop.
def db
@db ||= SQLite3::Database.new(path.to_s).tap do |db|
db.results_as_hash = true
db.instance_eval do
def tables
rows = execute "SELECT name FROM sqlite_master WHERE type='table';"
rows.map{|r| r['name']}
end
def column_syms_for_table(table)
r = prepare "SELECT * FROM #{table};"
r.columns.map &:intern
end
def method_missing(m, *args, &block)
super unless tables.include? m.to_s
columns = column_syms_for_table m
Table.new \
name: m.to_s,
columns: columns,
db: self
end
end
end
end
class Table
virtus :name, :columns, :db
# `name` - table name str
# `columns` - an array of symbols
# `db` - SQLite3::Database instance
def insert(hash)
sql = "INSERT INTO #{name} ( #{comma_sep_column_names} ) VALUES ( #{val_question_marks} )"
vals = vals_for_hash hash
db.execute sql, *vals
end
def count
db.execute("SELECT COUNT(*) FROM #{name};")[0][0]
end
private
def comma_sep_column_names
columns.join(', ')
end
def val_question_marks
comma_sep_column_names
.gsub(/\w+/, '?')
end
def vals_for_hash(hash)
columns.map {|cname| hash[cname] }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment