Skip to content

Instantly share code, notes, and snippets.

@akuhn
Created July 20, 2015 20:55
Show Gist options
  • Save akuhn/6488b84a7b037dc626d1 to your computer and use it in GitHub Desktop.
Save akuhn/6488b84a7b037dc626d1 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'colorize'
require 'pry'
class Eigenlogger
def debug?
true
end
def debug(message)
message.uncolorize =~ /^ (.*?) (.*)$/
time, sql = $1, $2
.gsub(/\b\d+\b/, &:blue)
.gsub(/"[^"]+"/, &:red)
.gsub(/\b[A-Z]+\b/, &:green)
puts "#{sql} #{time}"
end
def error(message)
binding.pry
end
end
ActiveRecord::Base.logger = Eigenlogger.new
class ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: ':memory:'
connection.create_table 'people' do |t|
t.string :name
t.integer :age
end
connection.create_table 'colors' do |t|
t.string :name
end
connection.create_table 'colors_people' do |t|
t.belongs_to :person
t.belongs_to :color
t.index %w(person_id color_id), unique: true
end
connection.create_table 'posts' do |t|
t.string :title
t.text :content
t.string :tags
t.belongs_to :person, index: true
end
end
class Person < ActiveRecord::Base
has_and_belongs_to_many :colors
has_many :posts
accepts_nested_attributes_for :posts
end
class Color < ActiveRecord::Base
has_and_belongs_to_many :people
end
class Eigencoder
def load(string)
string.to_s.split(',')
end
def dump(array)
array.join(',')
end
end
class Post < ActiveRecord::Base
belongs_to :person
serialize :tags, Eigencoder.new
end
Color.transaction do
%w(red yellow green blue purple).each do |name|
Color.create! name: name
end
end
jessie = Person.create!(
name: 'jessie',
colors: Color.where(name: %w(kazan babu)),
posts_attributes: [
{ title: 'Ate ate ate', content: 'omnomnom' },
{ title: 'Yo!', content: 'yadayada', tags: %w(wut lulz roflmao) },
],
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment