Skip to content

Commit

Permalink
hash long index names on translation tables
Browse files Browse the repository at this point in the history
  • Loading branch information
Clemens Kofler and Sven Fuchs committed Sep 14, 2009
1 parent cf754e4 commit 33d015c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
21 changes: 16 additions & 5 deletions lib/globalize/model/active_record/translated.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'digest/sha1'

module Globalize
module Model
class MigrationError < StandardError; end
Expand Down Expand Up @@ -80,12 +82,13 @@ def create_translation_table!(fields)
translated_fields.each do |f|
raise MigrationMissingTranslatedField, "Missing translated field #{f}" unless fields[f]
end

fields.each do |name, type|
if translated_fields.include?(name) && ![:string, :text].include?(type)
raise BadMigrationFieldType, "Bad field type for #{name}, should be :string or :text"
end
end
translation_table_name = self.name.underscore + '_translations'

self.connection.create_table(translation_table_name) do |t|
t.references self.table_name.singularize
t.string :locale
Expand All @@ -95,9 +98,17 @@ def create_translation_table!(fields)
t.timestamps
end

self.connection.add_index(
translation_table_name, "#{self.table_name.singularize}_id"
)
self.connection.add_index(translation_table_name, "#{self.table_name.singularize}_id", :name => translation_index_name)
end

def translation_table_name
self.name.underscore + '_translations'
end

def translation_index_name
# FIXME what's the max size of an index name?
index_name = "index_#{translation_table_name}_on_#{self.table_name.singularize}_id"
index_name.size < 50 ? index_name : "index_#{Digest::SHA1.hexdigest(index_name)}"
end

def drop_translation_table!
Expand Down Expand Up @@ -137,7 +148,7 @@ def update_globalize_record
end

def translated_locales
globalize_translations.scoped(:select => 'DISTINCT locale').map do |translation|
globalize_translations.scoped(:select => 'DISTINCT locale').map do |translation|
translation.locale.to_sym
end
end
Expand Down
14 changes: 14 additions & 0 deletions test/model/active_record/migration_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,19 @@ def setup
Blog.drop_translation_table!
end
end

test "translation_index_name returns a readable index name when it's not longer than 50 characters" do
assert_equal 'index_post_translations_on_post_id', Post.send(:translation_index_name)
end

test "translation_index_name returns a hashed index name when it's longer than 50 characters" do
class UltraLongModelName1337Haxx0rWeirdShit < ActiveRecord::Base
translates :foo
end
expected = 'index_699fca3525afc23e43c94b13b91eb7e9bba2cde9'
actual = UltraLongModelName1337Haxx0rWeirdShit.send(:translation_index_name)

assert_equal expected, actual
end

end

0 comments on commit 33d015c

Please sign in to comment.