Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

named scope #with_translations

  • Loading branch information...
commit 96d5f72b98045230cc148c47fe527701928bda48 1 parent 63f2037
@svenfuchs svenfuchs authored
View
30 lib/globalize/active_record.rb
@@ -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
@@ -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
@@ -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
View
5 test/active_record/translates_test.rb
@@ -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
View
1  test/test_helper.rb
@@ -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)
Please sign in to comment.
Something went wrong with that request. Please try again.