Skip to content

Instantly share code, notes, and snippets.

@NigoroJr
Created June 19, 2015 00:42
Show Gist options
  • Select an option

  • Save NigoroJr/6056d20f9db9e9627a3c to your computer and use it in GitHub Desktop.

Select an option

Save NigoroJr/6056d20f9db9e9627a3c to your computer and use it in GitHub Desktop.
Stupid sample script for ActiveRecord
#!/usr/bin/env ruby
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'sample.db'
)
class InitialSchema < ActiveRecord::Migration
def up
create_table :series do |t|
t.string :name
end
end
def down
drop_table :series
end
end
# Migrate
InitialSchema.migrate(:up) unless File.exists?('sample.db')
class Series < ActiveRecord::Base
end
def help
puts <<EOF
d <name> delete <name> from database
l list all entries
q quit
h show this help
! <name> force create
EOF
end
def add(name, force = false)
if force || Series.where(name: name).empty?
Series.create(name: name)
puts "Added entry: #{name}"
else
puts "Name: #{name} already exists!"
end
end
def delete(name)
# If integer is given
if name.to_i.to_s == name
Series.find(name.to_i).delete
else
Series.where(name: name).delete_all
end
puts "#{name} deleted"
end
loop do
print 'Enter name (h for help): '
input = gets.chomp
cmd, *names = input.split(' ')
case cmd
when 'h'
help
when 'd'
names.each do |name|
delete(name)
end
when 'q'
break
when 'l'
# Print current database
Series.all.each do |entry|
printf "%2d: %s\n", entry.id, entry.name
end
when '!'
names.each do |name|
add(name, true)
end
else
input.split(' ').each do |name|
add(name)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment