Created
January 31, 2011 01:15
-
-
Save whalec/803505 to your computer and use it in GitHub Desktop.
how bag's might work in migrations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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