Skip to content

Instantly share code, notes, and snippets.

@whalec
Created January 31, 2011 01:15
Show Gist options
  • Select an option

  • Save whalec/803505 to your computer and use it in GitHub Desktop.

Select an option

Save whalec/803505 to your computer and use it in GitHub Desktop.
how bag's might work in migrations
class SetupDatabase < ActiveRecord::Migration
def self.up
create_table :categories do |t|
t.bag_for :category
t.references :sector
t.timestamps
end
add_bag_indexes_for(:categories)
end
end
module Bagman
module TableBuilder
def self.build_table(table, bag = nil)
table.text :bag
if bag
bag.columns.select{|c| c.options[:index] }.each do |column|
index_name = case column.options[:index]
when TrueClass
"index_#{column.name}"
else
options[:index]
end
table.string index_name
end
end
end
def self.add_indexes(table, table_name, bag)
bag.columns.select{|c| c.options[:index] }.each do |column|
index_name = case column.options[:index]
when TrueClass
"index_#{column.name}"
else
options[:index]
end
table.add_index(table_name, index_name)
end
end
end
end
class ActiveRecord::ConnectionAdapters::TableDefinition
def bag_for(klass_symbol)
klass = klass_symbol.to_s.classify.constantize
Bagman::TableBuilder.build_table(self, klass.bag)
end
end
module ActiveRecord::ConnectionAdapters::SchemaStatements
def add_bag_indexes_for(table)
klass = table.to_s.classify.constantize
table_name = table.to_s.pluralize.to_sym
Bagman::TableBuilder.add_indexes(self, table_name, klass.bag)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment