Skip to content

Commit

Permalink
named scope #with_translations
Browse files Browse the repository at this point in the history
  • Loading branch information
Sven Fuchs committed Dec 26, 2009
1 parent 63f2037 commit 96d5f72
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
30 changes: 25 additions & 5 deletions lib/globalize/active_record.rb
Expand Up @@ -48,14 +48,22 @@ def translates(*attr_names)
self.translation_class = ActiveRecord.build_translation_class(self, options)
self.translated_attribute_names = attr_names.map(&:to_sym)

include InstanceMethods
extend ClassMethods, Migration

after_save :save_translations!
has_many :translations, :class_name => translation_class.name,
:foreign_key => class_name.foreign_key,
:dependent => :delete_all,
:extend => HasManyExtensions

include InstanceMethods
extend ClassMethods, Migration
named_scope :with_translations, lambda { |locale|
conditions = required_attributes.map do |attribute|
"#{quoted_translation_table_name}.#{attribute} IS NOT NULL"
end
conditions << "#{quoted_translation_table_name}.locale = ?"
{ :include => :translations, :conditions => [conditions.join(' AND '), locale] }
}

attr_names.each { |attr_name| translated_attr_accessor(attr_name) }
end
Expand All @@ -82,6 +90,16 @@ def translation_table_name
translation_class.table_name
end

def quoted_translation_table_name
translation_class.quoted_table_name
end

def required_attributes
validations = reflect_on_all_validations.select do |validation|
validation.macro == :validates_presence_of
end.map(&:name)
end

def respond_to?(method)
method.to_s =~ /^find_by_(\w+)$/ && translated_attribute_names.include?($1.to_sym) || super
end
Expand Down Expand Up @@ -124,9 +142,11 @@ def globalize
end

def available_locales
translations.scoped(:select => 'DISTINCT locale').map do |translation|
translation.locale.to_sym
end
translations.scoped(:select => 'DISTINCT locale').map(&:locale)
end

def translated_locales
translations.map(&:locale)
end

def translated_attributes
Expand Down
5 changes: 5 additions & 0 deletions test/active_record/translates_test.rb
Expand Up @@ -26,6 +26,11 @@ def setup
assert_has_many Post, :translations
end

test 'defines a scope for retrieving locales that have complete translations' do
post = Post.create!(:subject => 'subject', :content => 'content')
assert_equal [:en], post.translated_locales
end

test 'sets the given attributes to translated_attribute_names' do
assert_equal [:subject, :content], Post.translated_attribute_names
end
Expand Down
1 change: 1 addition & 0 deletions test/test_helper.rb
Expand Up @@ -7,6 +7,7 @@
require 'active_support/test_case'
require 'mocha'
require 'globalize'
require 'validation_reflection'

config = { :adapter => 'sqlite3', :database => ':memory:' }
ActiveRecord::Base.establish_connection(config)
Expand Down

0 comments on commit 96d5f72

Please sign in to comment.