Permalink
Browse files

Take account of table_name_prefix option.

The Rails option for table_name_prefix and table_name_suffix means they
must be removed when doing a schema dump.
  • Loading branch information...
1 parent 968a112 commit f29d0f1e29d178c8f91d31579c9254e2884ce491 Kyle Stevens committed Aug 9, 2012
Showing with 17 additions and 3 deletions.
  1. +7 −3 lib/foreigner/schema_dumper.rb
  2. +10 −0 test/foreigner/schema_dumper_test.rb
View
10 lib/foreigner/schema_dumper.rb
@@ -8,11 +8,11 @@ module SchemaDumper
module ClassMethods
def dump_foreign_key(foreign_key)
- statement_parts = [ ('add_foreign_key ' + foreign_key.from_table.inspect) ]
- statement_parts << foreign_key.to_table.inspect
+ statement_parts = [ ('add_foreign_key ' + remove_prefix_and_suffix(foreign_key.from_table).inspect) ]
+ statement_parts << remove_prefix_and_suffix(foreign_key.to_table).inspect
statement_parts << (':name => ' + foreign_key.options[:name].inspect)
- if foreign_key.options[:column] != "#{foreign_key.to_table.singularize}_id"
+ if foreign_key.options[:column] != "#{remove_prefix_and_suffix(foreign_key.to_table).singularize}_id"
statement_parts << (':column => ' + foreign_key.options[:column].inspect)
end
if foreign_key.options[:primary_key] != 'id'
@@ -24,6 +24,10 @@ def dump_foreign_key(foreign_key)
statement_parts.join(', ')
end
+
+ def remove_prefix_and_suffix(table)
+ table.gsub(/^(#{ActiveRecord::Base.table_name_prefix})(.+)(#{ActiveRecord::Base.table_name_suffix})$/, "\\2")
+ end
end
def tables_with_foreign_keys(stream)
View
10 test/foreigner/schema_dumper_test.rb
@@ -48,6 +48,16 @@ def foreign_keys(table, stream)
assert_equal ['bar'].to_set, dumper.processed_tables.to_set
end
+ test 'removes table name suffix and prefix' do
+ begin
+ ActiveRecord::Base.table_name_prefix = 'pre_'
+ ActiveRecord::Base.table_name_suffix = '_suf'
+ assert_dump "add_foreign_key \"foos\", \"bars\", :name => \"lulz\"", Foreigner::ConnectionAdapters::ForeignKeyDefinition.new('pre_foos_suf', 'pre_bars_suf', column: 'bar_id', primary_key: 'id', name: 'lulz')
+ ensure
+ ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = ''
+ end
+ end
+
private
def assert_dump(expected, definition)
assert_equal expected, MockSchemaDumper.dump_foreign_key(definition)

0 comments on commit f29d0f1

Please sign in to comment.