Skip to content

Commit

Permalink
Take account of table_name_prefix option.
Browse files Browse the repository at this point in the history
The Rails option for table_name_prefix and table_name_suffix means they
must be removed when doing a schema dump.
  • Loading branch information
Kyle Stevens authored and Kyle Stevens committed Aug 9, 2012
1 parent 968a112 commit f29d0f1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/foreigner/schema_dumper.rb
Expand Up @@ -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'
Expand All @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions test/foreigner/schema_dumper_test.rb
Expand Up @@ -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)
Expand Down

0 comments on commit f29d0f1

Please sign in to comment.