lib/has_translations.rb in has_translations-0.3.1 vs lib/has_translations.rb in has_translations-0.3.2
- old
+ new
@@ -87,29 +87,37 @@
options.assert_valid_keys([:fallback, :reader, :writer, :nil])
translation_class_name = "#{self.model_name}Translation"
translation_class = translation_class_name.constantize
- belongs_to = self.model_name.demodulize.singularize.underscore.to_sym
+ belongs_to = self.model_name.demodulize.underscore.to_sym
write_inheritable_attribute :has_translations_options, options
class_inheritable_reader :has_translations_options
- send :define_method, :find_or_build_translation do |*args|
- locale = args.first.to_s
- build = args.second.present?
- find_translation(locale) || (build ? self.translations.build(:locale => locale) : self.translations.new(:locale => locale))
+ def find_or_create_translation(locale)
+ locale = locale.to_s
+ (find_translation(locale) || self.translations.new).tap do |t|
+ t.locale = locale
+ end
end
+ def find_or_build_translation(locale)
+ locale = locale.to_s
+ (find_translation(locale) || self.translations.build).tap do |t|
+ t.locale = locale
+ end
+ end
+
def translation(locale, fallback=has_translations_options[:fallback])
locale = locale.to_s
find_translation(locale) || (fallback && !translations.blank? ? translations.detect { |t| t.locale == I18n.default_locale.to_s } || translations.first : nil)
end
def all_translations
t = I18n.available_locales.map do |locale|
- [locale, find_or_build_translation(locale)]
+ [locale, find_or_create_translation(locale)]
end
ActiveSupport::OrderedHash[t]
end
def has_translation?(locale)
@@ -126,11 +134,11 @@
end
if options[:writer]
attrs.each do |name|
send :define_method, "#{name}=" do |value|
- translation = find_or_build_translation(I18n.locale, true)
+ translation = find_or_build_translation(I18n.locale)
translation.send(:"#{name}=", value)
end
end
end
@@ -138,15 +146,13 @@
translation_class.belongs_to belongs_to
translation_class.validates_presence_of :locale
translation_class.validates_uniqueness_of :locale, :scope => :"#{belongs_to}_id"
- # Rails 3.0
- if Object.const_defined?("ActiveModel")
- scope :translated, lambda { |locale| {:conditions => ["#{translation_class.table_name}.locale = ?", locale.to_s], :joins => :translations} }
- else
- named_scope :translated, lambda { |locale| {:conditions => ["#{translation_class.table_name}.locale = ?", locale.to_s], :joins => :translations} }
- end
+ # Workaround to support Rails 2
+ scope_method = if ActiveRecord::VERSION::MAJOR < 3 then :named_scope else :scope end
+
+ send scope_method, :translated, lambda { |locale| {:conditions => ["#{translation_class.table_name}.locale = ?", locale.to_s], :joins => :translations} }
private
def find_translation(locale)
locale = locale.to_s