Permalink
Browse files

Adding I18n translation support

  • Loading branch information...
1 parent f928d39 commit 99efee3b11c7b89653ebd56969bd3c043a55dbf1 @beerlington beerlington committed Aug 10, 2012
View
@@ -1,3 +1,4 @@
+require 'classy_enum/translation'
require 'classy_enum/collection'
require 'classy_enum/conversion'
require 'classy_enum/predicate'
@@ -5,6 +5,7 @@ class Base
include Comparable
include Conversion
include Predicate
+ include Translation
include Collection
class_attribute :base_class
@@ -68,7 +68,7 @@ def all
#
# Priority.select_options # => [["Low", "low"], ["Really High", "really_high"]]
def select_options
- all.map {|e| [e.to_s.titleize, e.to_s] }
+ all.map {|e| [e.text, e.to_s] }
end
end
@@ -0,0 +1,38 @@
+require 'i18n'
+
+module ClassyEnum
+ module Translation
+
+ # Returns a translated string of the enum type. Used internally to create
+ # the select_options array.
+ #
+ # Translation location is:
+ # locale.classy_enum.base_class.enum_string
+ #
+ # ==== Example
+ # # Create an Enum with some elements
+ # class Priority < ClassyEnum::Base
+ # end
+ #
+ # class Priority::Low < Priority; end
+ # class Priority::ReallyHigh < Priority; end
+ #
+ # # Default translations are `to_s.titlieze`
+ # Priority::Low.new.text # => 'Low'
+ # Priority::ReallyHigh.new.text # => 'Really High'
+ #
+ # # Assuming we have a translation defined for:
+ # # es.classy_enum.priority.low # => 'Bajo'
+ #
+ # Priority::Low.new.text # => 'Bajo'
+ def text
+ I18n.translate to_s, :scope => i18n_scope, :default => to_s.titleize
+ end
+
+ private
+
+ def i18n_scope
+ [:classy_enum, base_class.name.underscore]
+ end
+ end
+end
@@ -0,0 +1,43 @@
+require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
+
+class ClassyEnumTranslation < ClassyEnum::Base
+end
+
+class ClassyEnumTranslation::One < ClassyEnumTranslation
+end
+
+class ClassyEnumTranslation::Two < ClassyEnumTranslation
+end
+
+class ClassyEnumTranslation::Three < ClassyEnumTranslation
+end
+
+describe ClassyEnum::Translation do
+ subject { ClassyEnumTranslation::One.new }
+
+ before { I18n.reload! }
+
+ context '#text' do
+ context 'default' do
+ its(:text) { should == 'One' }
+ end
+
+ context 'en' do
+ before do
+ I18n.locale = :en
+ I18n.backend.store_translations :en, :classy_enum => {:classy_enum_translation => {:one => 'One!' } }
+ end
+
+ its(:text) { should == 'One!' }
+ end
+
+ context 'es' do
+ before do
+ I18n.locale = :es
+ I18n.backend.store_translations :es, :classy_enum => {:classy_enum_translation => {:one => 'Uno' } }
+ end
+
+ its(:text) { should == 'Uno' }
+ end
+ end
+end

0 comments on commit 99efee3

Please sign in to comment.